Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2010

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

Search the Archive

Re: Why Return[] does not work?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg109466] Re: Why Return[] does not work?
  • From: Raffy <adraffy at gmail.com>
  • Date: Wed, 28 Apr 2010 02:00:08 -0400 (EDT)
  • References: <hr6ihp$2f8$1@smc.vnet.net> <hr6la2$5im$1@smc.vnet.net>

On Apr 27, 5:28 am, Albert Retey <a... at gmx-topmail.de> wrote:
> Am 27.04.2010 13:41, schrieb Dims:
>
>
>
>
>
> > I wrote a function to check if two lists contain equal members:
>
> > Intersects[x_List,
> >   y_List] := (Do[(Print["Outer step ", xi];
> >     Do[(Print[xi, yi];
> >       If[xi == yi, (Print["Returning True"]; Return[True])]),=
 {yi,
> >       y}]), {xi, x}]; False)
>
> > But it returns False for interecting lists:
>
> > In[47]:= Intersects[{a, b}, {c, a}]
> > During evaluation of In[47]:= Outer step a
> > During evaluation of In[47]:= ac
> > During evaluation of In[47]:= aa
> > During evaluation of In[47]:= Returning True
> > During evaluation of In[47]:= Outer step b
> > During evaluation of In[47]:= bc
> > During evaluation of In[47]:= ba
> > Out[47]= False
>
> > Few questions:
>
> > 1) why does not Return[] interrupt the loops?
>
> Return behaves not as people expect in many circumstances. I found that
> I almost never really need it in my code because for every possible use
> case there are other mechanisms that work more reliable.
>
> > 2) is there better way to implement intersection check?
>
> There is Break which would be the natural choice to break loops,
> but I think usually Throw and Catch are the best choice in these situatio=
ns:
>
> Intersects[x_List, y_List] := Catch[
>   Do[
>    Print["Outer step ", xi];
>    Do[
>     Print[xi, yi];
>     If[xi == yi, Print["Returning True"]; Throw[True]],
>     {yi, y}
>     ], {xi, x}
>    ];
>   False
>   ]
>
> depending on what you try to achieve there might be better mechanisms
> than do loops which stop at certain conditions...
>
> hth,
>
> albert

Catch/Throw however cause overhead.

If you're return is just a boolean, and your control structure depth
is just 1, you could exploit the fact that: Do[Return[x],{1}] === x
and Do[Null,{1}] === Null.

intersects[x_List, y_List] := Do[If[xi == yi, Return[True]], {yi, y},
{xi, x}] === True;


  • Prev by Date: Re: Sphere formula
  • Next by Date: Re: Context Problem
  • Previous by thread: Re: Why Return[] does not work?
  • Next by thread: Re: Why Return[] does not work?