Re: ? Return[ ] in a Do loop ?
- To: mathgroup at smc.vnet.net
- Subject: [mg18555] Re: [mg18469] ? Return[ ] in a Do loop ?
- From: "Andrzej Kozlowski" <andrzej at tuins.ac.jp>
- Date: Sat, 10 Jul 1999 02:18:48 -0400
- Sender: owner-wri-mathgroup at wolfram.com
As they say, it's is not a bug it's a feature! Look at the folowing
examples:
In[1]:=
While[True, Return[1]]
Out[1]=
Return[1]
In[2]:=
Do[Return[1], {i, 1}]
Out[2]=
1
It is because the While loop returns not 1 but Return[1] that it will exit
the entire function rather than jus the loop. But of course this is not
always convenient: often you would like to return an actual value rather
than Return[value]. This is more likely to be the case in the case of Do
loops than While loops, because Do loops are more often used alone than
While and For loops.
I any case, you can always get the behavoiour you desire with the Do loop by
using Throw and Catch instead of Return:
In[2]:=
firstPosition[cand_List, target_] :=
Module[{i},
Catch[Do[ If[cand[[i]] == target, Throw[i]],
{i, 1, Length[cand]}
];
-1]
]
In[3]:=
firstPosition[{1, 1, 2, 3, 4}, 2]
Out[3]=
3
--
Andrzej Kozlowski
Toyama International University
JAPAN
http://sigma.tuins.ac.jp
http://eri2.tuins.ac.jp
----------
>From: "DongGook Park" <park at isrc.qut.edu.au>
To: mathgroup at smc.vnet.net
>To: mathgroup at smc.vnet.net
>Subject: [mg18555] [mg18469] ? Return[ ] in a Do loop ?
>Date: Thu, Jul 8, 1999, 12:08 PM
>
> 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
>