A simple function that adds 3 to all input and return a list containing the input and the output:
test[h_] := {
g = h + 3;
Return[{h,g}];
};
When I evaluate it with test[5]
, I get:
{Return[{5, 8}]}
but I would like to get: {5, 8}
You have the wrong type of brackets. Your version is returning a List
(which retains the Return
object).
Also, Return
is used to break out of control structures. Basic return of variables is automatic; you don't need to use Return
in your example.
Here the bracket are corrected.
test[h_] := (
g = h + 3;
Return[{h, g}];)
test[5]
{5, 8}
The above is actually returning from the expression group before it hits the suppressing semi-colon.
Without Return
the semi-colon suppresses output.
test[h_] := (
g = h + 3;
{h, g};)
test[5]
null
To fix this you can just omit the final semi-colon.
test[h_] := (
g = h + 3;
{h, g})
test[5]
{5, 8}
Why did Return appear?
Comparing two simple cases
test[h_] := Return[{h, h + 3}]
test[5]
{5, 8}
test[h_] := {Return[{h, h + 3}]}
test[5]
{Return[{5, 8}]}
The reason is mentioned here
The very last step of the evaluation loop is ...
"Discard the head Return, if present, for expressions generated through application of user-defined rules."
In the second case the head is List
so the Return
is not discarded.
Module
is mainly used for localizing variables. In henry's example g
is localized and will not affect another g
outside the module.
$\endgroup$
Commented
Apr 13, 2018 at 15:16
test[5][[0]]
I get List
as output...
$\endgroup$
test[5][[1]]
to obtain 5. The zeroth item is the Head : see the Head - Properties & Relations section : "The head is the part with index 0".
$\endgroup$
Commented
Feb 6, 2021 at 10:29
You can use modules:
test[h_] := Module[{g},
g = h + 3;
Return[{h, g}]];
As suggested by @m_goldberg the function can be simplified:
test[h_] := Module[{g},
g = h + 3;
{h, g}];
Return
and made the last line in the module just {h, g}
$\endgroup$
Commented
Apr 13, 2018 at 15:03
test[h_] := {h, h + 3}
Return
is only needed for special purposes in Mathematica. $\endgroup$