17
$\begingroup$

In the following simple example

MyMod := Module[{i},
  Do[
    Return[1],
    {i, 3}
  ];
  Print["test"]
]

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

In[1]:= a = MyMod
       test

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?

$\endgroup$

1 Answer 1

20
$\begingroup$

You need to use Module option on return

myMod := Module[{i},
  Do[
   Return[1, Module],
   {i, 3}
   ];
  Print["test"]
  ]

and now

 myMod
 (* 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.

update

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

$\endgroup$
5
  • $\begingroup$ Thank you, can I ask if you know if Return has always worked this way? $\endgroup$
    – enzotib
    Commented Mar 23, 2014 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
    Commented Mar 23, 2014 at 17:04
  • $\begingroup$ Also, I cannot find any reference to a possible second parameter to Return in that document. $\endgroup$
    – enzotib
    Commented Mar 23, 2014 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
    Commented Mar 23, 2014 at 17:06
  • 5
    $\begingroup$ @enzotib The documentation is well hidden. Also see the discussion here. $\endgroup$
    – WReach
    Commented Mar 23, 2014 at 17:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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