4
$\begingroup$

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?

$\endgroup$
  • 6
    $\begingroup$ Best practice is the 2nd (no 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 that Return returns from the function, not from the Module. If you had something wrapping the Module, the behaviour would be different. $\endgroup$ – Szabolcs Aug 31 at 18:17
10
$\begingroup$

The use case for Return is not to return a value at the end of a scoping construct like Module or Block, but to return something from the middle of the construct:

func[x_] := Module[
    {answer1,answer2},
    <code>
    If[isValid[answer1],
        Return[answer1, Module]
    ];
    <more code>
    answer2
]

Here I check a whether some condition is satisfied, and if so I exit the Module early. This could be achieved with a Catch and Throw, but I tend to reserve that more for errors and exceptions. Here I view the Return as a normal operation, and not exceptional.

The caveat here is that the 2-argument form of Return, where the second argument says what to return from, is severely under-documented.

$\endgroup$
  • 4
    $\begingroup$ where the second argument says what to return from, is not documented. actually it is documented, just hidden :) From returning-a-value-from-a-module in the comments there below the answer, WReach gave the link which is here Where it says on that WRI page the following: The second argument is used here to specify that the return should be from the enclosing Module $\endgroup$ – Nasser Sep 1 at 4:21
  • 2
    $\begingroup$ That is hilarious, that we document the error message and not the usage. $\endgroup$ – Jason B. Sep 1 at 13:54

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.