0

I wish that the Mathematica documentation for the If command showed examples that have more than one statement for the t and f responses.

All three of these work:

No parentheses or braces:

Module[{x, y, z},
 If[3 === 4,
  x = 1;
  y = 2;
  z = x + y,
  x = 5;
  y = 9;
  z = x + y];
 Print[z]]

Use parentheses:

Module[{x, y, z},
 If[3 === 4,
  (x = 1;
   y = 2;
   z = x + y),
  (x = 5;
   y = 9;
   z = x + y)];
 Print[z]]

Use braces:

Module[{x, y, z},
 If[3 === 4,
  {x = 1;
   y = 2;
   z = x + y},
  {x = 5;
   y = 9;
   z = x + y}];
 Print[z]]

All give output 14.

Is it OK to use each of these three? If so, what do users prefer?

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
David
  • 14,883
  • 4
  • 44
  • 117
  • 1
    The first and second are identical. The third is different in that it returns the list {z} (Also note that you generally don't need the Print statement at the end. A plain z will do if you're working interactively.). All three work by making a CompoundExpression. (a;b;c really is just CompoundExpression[a, b, c]). You only need parens to resolve ambiguity. The first is therefore probably the cleanest. The third is definitely not what you want. (unless you are trying to build a list). – b3m2a1 May 27 '17 at 04:37
  • @MB1965 Nice answer. But you said The third is different in that it returns the list {z}. I think you meant to say The third is different in that it returns the list {z} if you don't use the Print command. Still, I really appreciate this answer. – David May 27 '17 at 05:02
  • 3
    I mean the If returns that. The Print command is really pretty much meaningless here. (By which I mean leaving it out will not change what you see in any way -- except that you'll have and "Output" cell instead of "Print" cell). – b3m2a1 May 27 '17 at 05:04

2 Answers2

2

I did not initially post an answer because I don't use a single format for If statements and it is rare that I use them to perform a series of Sets. If I did I would probably formulate it more like this:

Module[{x, y, z},
  {x, y} = If[3 === 4, {1, 2}, {5, 9}];
  z = x + y
]

If you prefer something more along the lines of UnchartedWorks' answer I see no need to pass parameters, e.g.:

Module[{x, y, z, f, g},
  f[] := (x = 1; y = 2; z = x + y);
  g[] := (x = 5; y = 9; z = x + y);
  If[3 === 4, f[], g[]]
]

By convension I use f[] rather than bare f for any parameter-free subroutine as among other things this lets one pass the name f without triggering unwanted evaluation.

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
1
Module[{x, y, z, f, g, h},
 f[x, y, z] := {x = 1; y = 2; z = x + y};
 g[x, y, z] := {x = 5; y = 9; z = x + y};
 h[x, y, z] := If[3 === 4, f[x, y, z], g[x, y, z]] // First // Print;
 h[x, y, z]]
webcpu
  • 3,182
  • 12
  • 17