Mathematica [Mathematica] Confusion with Return[]

AI Thread Summary
The discussion centers around the behavior of the Return[] function in two different function definitions in Mathematica. The user notes a discrepancy where calling a function defined with Function[] returns "Return[a]", while a function defined with the pattern f[x_] returns the value "a" as expected. This leads to the conclusion that there is a fundamental difference between these two notations, which may not be intuitive. The user highlights that the Return[] function does not evaluate properly in the first case, even though it recognizes the call and does not proceed to the next command. The issue appears to persist across multiple versions of Mathematica, specifically 7.0.1 and 8. The discussion concludes with the user finding a workaround by using the f[x_]:=body notation, which resolves the problem for their needs.
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:

Similar threads

Replies
1
Views
2K
Replies
19
Views
2K
Replies
1
Views
1K
Replies
10
Views
2K
Replies
0
Views
493
Replies
4
Views
1K
Replies
2
Views
2K
Replies
6
Views
4K
Back
Top