5
$\begingroup$

Is there a convention for writing If expressions to visually differentiate between the different arguments? For example:

If[conditional,
    expr1;
    expr2;
    expr3,
    expr4;
    expr5
]

In this code, it is very difficult at a glance to notice that the , after expr3 marks the separation between the true and false parts of the expression. Using Extend Selection works, but can only highlight one full potion at a times, making examining nested statements cumbersome. A potential solution would be to abstract the expressions into multiple functions, but when the code is only a few lines long this seems like overkill. Wrapping each argument in a singe function, like

If[conditional,
    Module[{},
        expr1;
        expr2;
        expr3
    ],
    Module[{},
        expr4;
        expr5
    ]
]

works somewhat, but does increase indentation, which is annoying for nested expressions

Is there a better solution, or should I just pick something and stick with it?

$\endgroup$
  • $\begingroup$ I wonder is there a clean want to change the symbols? Especially on my linux system the semicolon and comma are very hard to distinguish. $\endgroup$ – george2079 Dec 2 '14 at 18:31
8
$\begingroup$

Several users place commas in the beginning of lines instead of at the end, which makes it a little bit easier to differentiate when a new argument begins. Here are two more styles that you may consider:

If[(
  expr1;
  expr2;
  expr3
  )
 ,
 (
  expr3;
  expr4;
  expr5
  )
 ]

And

If[
 CompoundExpression[
  expr1
  , expr2
  , expr3
  ],
 CompoundExpression[
  expr4
  , expr5
  , expr6
  ]
 ]

Eschewing shorthand notation such as ; for the proper name of the function is useful in many scenarios. When my code looks hard to read I often try to replace /@ with Map and so on.

| improve this answer | |
$\endgroup$
  • 2
    $\begingroup$ +1, I also use a comma on a separate line (as in your first example), to more clearly delimit arguments of "functions" like If, While, Switch, etc. $\endgroup$ – Szabolcs Dec 2 '14 at 17:36
5
$\begingroup$
 If[conditional (*then*),
     expr1;
     expr2;
     expr3
   (*else*),
     expr4;
     expr5
  (*endif*) ]
| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.