MathGroup Archive 2009

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

Search the Archive

Re: Return in function

  • To: mathgroup at smc.vnet.net
  • Subject: [mg106018] Re: Return in function
  • From: "Norbert P." <bertapozar at gmail.com>
  • Date: Wed, 30 Dec 2009 04:15:36 -0500 (EST)
  • References: <hftbe9$cjh$1@smc.vnet.net>

On Dec 11, 3:46 am, dh <d... at metrohm.com> wrote:
> Version 7.0.1
>
> Hello,
>
> I am not sure if this is a feature or a bug. If you use Return in an
>
> anonymous function, not only the return value is returned, but also
>
> "Return" itself. Consider:
>
> (If[# == 2, Return[a]; #, #]) & /@ {1, 2, 3}
>
> this gives:
>
> {1, Return[a], 3}
>
> The same thing happens with:
>
> Function[x, If[x == 2, Return[a]; x, x]] /@ {1, 2, 3}
>
> However, the following works as expected:
>
> f[x_] := (If[x == 2, Return[a]; x, x]);
>
> f /@ {1, 2, 3}
>
> Daniel

Even though I think that it's a bad habit to use Return, it might be
useful at times. And since it's been in Mathematica since the version
1, it should've been fixed a long time ago.

To make the code even simpler, try (version 6.0.2):

In[1]:= f[]:=(Return[a];1);

In[2]:= f[]
Out[2]= a

It works as expected. Now try

In[3]:= (Return[a];1)&[]
Out[3]= Return[a]

This is obviously a bug. One would expect to see "a" if Return worked
properly, or "1" if Return didn't work inside Function, but only in
definitions such as f[]:=... above.

I get a similar result using RuleDelayed as in

In[4]:= 2/. 2:>(Return[a];1)
Out[4]= Return[a]

The documentation is also contradictory. In the description of Return,
there's an example that shows that Return exists only the innermost
loop (construct) such as Do. Much like Break[], why isn't there Break
[expr] instead? But in tutorial/LoopsAndControlStructures they say:
 Return[expr]	return the value expr, exiting all procedures and loops
in a function

Best,
Norbert


  • Prev by Date: Re: bug in RandomChoice if weight is zero?
  • Next by Date: Abs''[1]
  • Previous by thread: Re: Return in function
  • Next by thread: Re: Re: Return in function