# Function with Return

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}

• Just write test[h_] := {h, h + 3} Return is only needed for special purposes in Mathematica. – m_goldberg Apr 13 '18 at 15:06

## 2 Answers

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.

• Nice ! when do I have to use module then, as suggested by @henry ? – james Apr 13 '18 at 15:12
• Module is mainly used for localizing variables. In henry's example g is localized and will not affect another g outside the module. – Chris Degnen Apr 13 '18 at 15:16

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}];

• This answer would be better if you removed Return and made the last line in the module just {h, g} – m_goldberg Apr 13 '18 at 15:03
• @m_goldberg added it. Thanks for the input. – henry Apr 14 '18 at 18:14