Re: Why Return[] does not work?
- To: mathgroup at smc.vnet.net
- Subject: [mg109454] Re: Why Return[] does not work?
- From: Albert Retey <awnl at gmx-topmail.de>
- Date: Tue, 27 Apr 2010 08:28:42 -0400 (EDT)
- Organization: CNNTP
- References: <hr6ihp$2f8$1@smc.vnet.net>
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 situations: 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