[Mathematica] Confusion with Return[]

  • Context: Mathematica 
  • Thread starter Thread starter guerom00
  • Start date Start date
  • Tags Tags
    Confusion Mathematica
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
4 replies · 3K views
guerom00
Messages
90
Reaction score
0
Hello all,

There's something I don't understand when using Return[]…

Take this input :

f := Function[{x}, (If[x > 5, Return[a]]; x + 3)];
g[x_] := (If[x > 5, Return[a]]; x + 3);

and this output :

In[25]:= f[6]
g[6]

Out[25]= Return[a]

Out[26]= a

In one case, it returns the value "a", as expected. But in the other case, it writes explicitly "Return[a]". Why ? I don't understand...

Thanks in advance.
 
Physics news on Phys.org
I think the bottom line is that there must be a difference between defining a function using the notation f=Function[x,body] and the notation f[x_]=body. But I don't know, I thought those two notations were equivalent...
 
It looks like a bug to me...

Code:
In[1]:= f:=Function[{x},(If[x>5,Return[a]];x+3)];
       g[x_]:=(If[x>5,Return[a]];x+3);

In[3]:= f[6]//Trace
Out[3]= {{f,Function[{x},If[x>5,Return[a]];x+3]},Function[{x},If[x>5,Return[a]];x+3][6],If[6>5,Return[a]];6+3,{{6>5,True},If[True,Return[a]],Return[a]},Return[a]}

In[4]:= g[6]//Trace
Out[4]= {g[6],If[6>5,Return[a]];6+3,{{6>5,True},If[True,Return[a]],Return[a]},Return[a],a}

The point of interest is at the very end of the trace:
Code:
f:...  If[True,Return[a]],Return[a]},Return[a]}
g:...  If[True,Return[a]],Return[a]},Return[a],a}
Which is strange. Obviously it is recognizing the Return[] call, because otherwise it would move on to the next command, x+3... as happens when x<=5. It's just not evaluating Return[a] properly.

What version are you running?
 
OK, thanks :)
Well, at least for my purpose, using the f[x_]:=body notation solves the issue…
@Simon_Tyler: I can reproduce this issue both in 7.0.1 and 8 on a Mac.
 
Last edited: