I am a bit confused on the use of Return
in either Block
or Module
when defining a custom function that is used a lot. For instance, The two simple functions (not using initialisation to examplify)
f1[x_] := Module[{y},y=x+1; Return[y];];
f2[x_] := Module[{y},y=x+1; y];
I am familiar with the differences between Module
and Block
---see e.g. here---but I don't really understand what the difference between f1
and f2
are in the present case. As someone familiar with other languages, the first seems more natural than the second, especially with respect to the absence of a final semi-colon in the module.
I have noticed that with Return
I get a bunch of variables y$1
, y$2
, ... that get out of scope and not in the other case, but I haven't used it enough to see if it happens also in that case.
Is there a fundamental difference between those two functions, and what is considered best practice?
Return
).Return
is a bit foreign to how Mathematica works, and also redundant here. There is absolutely no reason to add it (it doesn't improve readability for someone comfortable with Mathematica—quite the opposite). Note thatReturn
returns from the function, not from theModule
. If you had something wrapping theModule
, the behaviour would be different. $\endgroup$