In the following simple example

MyMod := Module[{i},
    {i, 3}

I expected the module to exit on Return and never reach the Print, instead I have

In[1]:= a = MyMod

I am sure I always used the former expected logic in the past.
I lost my memory or is it changed something in the way Return works?


You need to use Module option on return

myMod := Module[{i},
   Return[1, Module],
   {i, 3}

and now

 (* 1 *)

This is because Return only returns from nearest enclosure, which was Do in your case and not from the whole Module unless you use the Module second option to Return. This is different from other languages that you might be familiar with.

See possible options here https://reference.wolfram.com/mathematica/ref/Return.html for more information.


To answer the question in comment below if Return has always worked this way?

Using V 2.2 of Mathematica, the Module option was not supported since I get an error. So this option was added sometime after version 2.2. May be someone else knows when it was added.

ps. looking at bottom of the Return help page, it says it was updated in 1996 (version 3.0), so I would assume this is when the option Module was added.

Mathematica graphics

|improve this answer|||||
  • $\begingroup$ Thank you, can I ask if you know if Return has always worked this way? $\endgroup$ – enzotib Mar 23 '14 at 17:02
  • $\begingroup$ @enzotib Let me reboot my version 2.2 of Mathematica and see. I can't answer this question right now. I would think it always worked this way in Mathematica, but I do not know. May be someone else would. But I will check 2.2 to see. $\endgroup$ – Nasser Mar 23 '14 at 17:04
  • $\begingroup$ Also, I cannot find any reference to a possible second parameter to Return in that document. $\endgroup$ – enzotib Mar 23 '14 at 17:05
  • 1
    $\begingroup$ @enzotib it a secret option :) I am sure it is there somewhere, but need more time to find it now. $\endgroup$ – Nasser Mar 23 '14 at 17:06
  • 5
    $\begingroup$ @enzotib The documentation is well hidden. Also see the discussion here. $\endgroup$ – WReach Mar 23 '14 at 17:37

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.