MathGroup Archive 1999

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

Search the Archive

? Return[ ] in a Do loop ?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg18469] ? Return[ ] in a Do loop ?
  • From: "DongGook Park" <park at isrc.qut.edu.au>
  • Date: Wed, 7 Jul 1999 23:08:36 -0400
  • Sender: owner-wri-mathgroup at wolfram.com

Hi,

I have found a strange behaviour of Return[ ] command when it is located in
a Do[ ] loop. That is, Return[ ] in a Do[ ] loop does not exits the
"function" but just the "Do loop". Fortunately(?), I have found that
eturn[ ] behaved desirably in While and For loops. I am quite confused and
wondering if these different behaviours of Return[] is as designed or just a
bug. Can anyone explain this behaviour?

Please check the following Mathematica scripts.

-------- Return in Do loop

In[1]:=
firstPosition[cand_List, target_] :=
Module[{i},
	Do[ Print[i]; If[cand[[i]] == target, Return[i]],
	    {i, 1, Length[cand]}
	];
	-1
]

In[2]:=
firstPosition[{1,1,2,3,4},2]

1
2
3

Out[2]=
-1


-------- Return in While loop

In[3]:=
firstPosition[cand_List, target_] :=
Module[{i=1},
	While[i <= Length[cand],

	      If[cand[[i]] == target, Return[i]];
	      i++
	];
	-1
]

In[4]:=
firstPosition[{1,1,2,3,4},2]

Out[4]=
3


-------- Return in For loop

In[5]:=
firstPosition[cand_List, target_] :=
Module[{i},
	For[i = 1,
	    i <= Length[cand],
	    i++,

	    If[cand[[i]] == target, Return[i]]
	];
	-1
]

In[6]:=
firstPosition[{1,1,2,3,4},2]

Out[6]=
3

----------

Thanks,
DongGook Park



  • Prev by Date: Re: Wheel mouse under X.
  • Next by Date: RE: ExpIntegralEi
  • Previous by thread: Re: notebook expression by Email
  • Next by thread: Re: ? Return[ ] in a Do loop ?