Re: First question
- To: mathgroup at smc.vnet.net
- Subject: [mg52131] Re: First question
- From: Bill Rowe <readnewsciv at earthlink.net>
- Date: Thu, 11 Nov 2004 04:53:20 -0500 (EST)
- Sender: owner-wri-mathgroup at wolfram.com
On 11/10/04 at 4:45 AM, dto_mba at skynet.be wrote:
>How to exit directly and immediately a module from inside a loop
>with a certain value ? Return seems not to work.
>Example:
>lmaa := Module[
>{},
> Do[
> If[i > 3, Return[{"from inside"}]],
> {i, 1, 5}
> ];
> Return[{"not from inside"}]
>]
>lmaa
>{not from inside}
Your problem isn't that Return isn't working but that it only causes an exit from one level of control structure. What happens is as follows when i = 4:
The Do loop is exited then the next line of code
Return[{"not from inside"}] is executed causing the module to be exited with the results of this line of code.
Change your code as follows:
maa[m_] :=
Module[{n = 0},
Do[If[i > m, n = i; Return[{" from inside"}]],
{i, 1, 5}];
Return[{StringJoin["n is ", ToString[n]],"not from inside"}]]
and see
maa[3]
{"n is 4", "not from inside"}
demonstrating Return does work as advertised.
If you want to exit from the Do loop and the Module when i becomes 4, you need to test the value of i immediately after exiting the Do loop and exit the Module based on that test.
--
To reply via email subtract one hundred and four