Mathematica 9 is now available
Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
2004
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2004

[Date Index] [Thread Index] [Author Index]

Search the Archive

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


  • Prev by Date: Re: Re: Poles and Complex Factoring
  • Next by Date: minimal Pisot tile {2,3] type definition in Mathematic
  • Previous by thread: Re: Re: First question
  • Next by thread: Re: First question