8
$\begingroup$

Why doesn't Return actually return a value in a Function? E.g.,

ClearAll[f]
f = Function[x, Return[x + 1]];
f[1]  (* Return[2] *)

Contrast with a pattern-defined function:

ClearAll[f]
f[x_] := Return[x + 1]
f[1]  (* 2 *)

After reading How does Return work? it seems that the answer turns on an odd behavioral difference in the presence of Set and SetDelayed, but (i) can one deduce this difference from the documentation, and (ii) is there a clear motivation for this difference?

$\endgroup$
6
$\begingroup$

(i) can one deduce this difference from the documentation?

No. The documentation article on Return is scandalously inadequate.

(ii) is there a clear motivation for this difference?

Taken literally, I don't think this is a reasonable question for this site. It asks us to explain the thinking of the people who implemented Return. But perhaps you meant it to be interpreted as "is there any benefit to Mathematica users from this behavior?" My answer to this interpretation of (ii) is that I think there is: it indicates that you have called Return in a situation where the developers intended it should not be called.

It always possible to write code so it avoids the behavior that bothers you. In your case:

ClearAll[f]
f = Function[x, Do[Return[x + 1], {1}]];
f[1]

2

If you absolutely must use Return in a situation where it will not be stripped from the returned expression, you can always wrap it in Do as shown above. It will not add much to the evaluation cost.

$\endgroup$
  • $\begingroup$ My second question does not translate well as "is there any benefit to Mathematica users from this behavior?" It is related to this, but not in the way that your follow on would suggest. A "clear motivation" would be an aspect of the core structure of WL that would lead someone with good understanding of the language to expect that when a Return command was introduced it should work as it currently does. It is definitely not a request for psychoanalysis of the developers. $\endgroup$ – Alan Sep 28 '16 at 17:55
  • 3
    $\begingroup$ I know at least one developer who would require psychoanalysis, possibly forensic in nature, were he to ever again try to carefully consider the inner workings of Return. $\endgroup$ – Daniel Lichtblau Sep 28 '16 at 19:09
  • 1
    $\begingroup$ @DanielLichtblau count one more, although since I never looked at the actual implementation, I probably don't qualify. $\endgroup$ – Leonid Shifrin Sep 28 '16 at 19:10

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.