12
$\begingroup$

should I write the program like this:

f[x_]:=x^2; 
g[x_]:=x+2;

or should I write the program like this:

f[x_]:=x^2
g[x_]:=x+2

Which one is good practice, does any of them have side effect?

$\endgroup$
2
  • $\begingroup$ No difference that I know, except that you can put multiple pieces of code on one line, when they are separated by semicolons. $\endgroup$
    – bbgodfrey
    Commented Jul 10, 2016 at 1:32
  • 1
    $\begingroup$ One trivial side effect is that a semicolon affects indentation in the front end. $\endgroup$
    – Michael E2
    Commented Jul 10, 2016 at 2:32

1 Answer 1

18
$\begingroup$

There is a difference between SetDelayed (:=) with or without semicolon, but it usually doesn't matter. The semicolon is actually a CompoundExpression which has Null as its last element - that's the one that gets returned.

But SetDelayed returns Null, too. So the results returned with or without semicolon are the same.

An exception to this statement occurs when the SetDelayed fails, as in the case 2:=1 where I try to assign a value in a forbidden way. Then SetDelayed returns $Failed instead of Null. But if you end the := assignment with a semicolon, then the result $Failed is not returned, because the Null is still the last expression in CompoundExpression. Therefore, if you're doing := inside a structure that watches for the occurrence of $Failed in the assignment, you can't use the semicolon. Here is a test:

Print[2 := 1];
Print[2 := 1;]

setdelayed

In normal usage in the notebook, I don't think there's any reason to use the semicolon after :=. However, one more case where I find it safer to use semicolons at the ends of such lines is when the code is not in a notebook but in a text file that may be read on different platforms, where line breaks could potentially be gobbled up so that the semicolon is a safety measure, preventing lines from unintentionally being merged into one.

$\endgroup$
4
  • $\begingroup$ Jens, I have marked this question as a duplicate. Please let me know if you disagree. $\endgroup$
    – Mr.Wizard
    Commented Jul 10, 2016 at 11:59
  • $\begingroup$ @Mr.Wizard You're right, I think you covered everything there, and even mentioned SetDelayed. I must have overlooked that thread. $\endgroup$
    – Jens
    Commented Jul 10, 2016 at 15:40
  • $\begingroup$ Someone is using M11... ;-) $\endgroup$
    – P. Fonseca
    Commented Jul 12, 2016 at 12:02
  • $\begingroup$ @P.Fonseca Yes, don't you love the stylish messages? $\endgroup$
    – Jens
    Commented Jul 12, 2016 at 14:58

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