MathGroup Archive 2009

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

Search the Archive

Re: Return in function

  • To: mathgroup at smc.vnet.net
  • Subject: [mg105695] Re: [mg105621] Return in function
  • From: Leonid Shifrin <lshifr at gmail.com>
  • Date: Wed, 16 Dec 2009 06:15:46 -0500 (EST)
  • References: <200912111146.GAA12933@smc.vnet.net>

Hi Daniel,

My feeling is that this is not a bug.

There are two possible outcomes for any expression wrapped in Return: either
it is inside some lexical  (or dynamic) scoping construct for which the
action of Return is defined - and then Return disappears as a part of
breaking-out-of-the-scoping-construct procedure, or it is not and then it is
just a symbolic expression like any other.  It seems like neither Function
nor CompoundExpression  are  considered  by Mathematica as the scoping
constructs for which the action of Return is defined as for example for
Module, Block, With, etc.

Under this assumption, your puzzle can be reduced to a simpler one:

In[1]:=
Clear[a,b,c];
c=(Return[a];3)

Out[1]= Return[a]

In[2]:=
b:=(Return[a];3)

In[3]:= b

Out[3]= a

The latter discrepancy can be explained by consulting the exact rules of the
evaluation procedure. Lacking a more up-to-date account, I cite here David
Withoff's "Mathematica internals" of 1992:

The very last step of the evaluation loop is (Chapter 3 - evaluation, p. 7,
on the bottom):

"Discard the head Return, if present, for expressions generated through
application of user-defined rules."

Thus, when you use SetDelayed, you create user-defined delayed rule and then
Return is discarded, while for "direct" evaluation like

In[4]:= Return[a]

Out[4]= Return[a]

it is not.

At least, things seem to work as documented in Withoff's technical report.
One thing that would be nice to have is a complete list of scoping
constructs for which Return is discarded when whatever it is wrapped around
is returned from that scoping construct.

Regards,
Leonid




On Fri, Dec 11, 2009 at 3:46 AM, dh <dh 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
>
>
>


  • Prev by Date: Re: Re: Animation with Sound in Mathematica?
  • Next by Date: Re: Re: Return in function
  • Previous by thread: Re: Return in function
  • Next by thread: Re: Return in function