5
$\begingroup$

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}

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

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.

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

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}];
$\endgroup$
  • 2
    $\begingroup$ This answer would be better if you removed Return and made the last line in the module just {h, g} $\endgroup$ – m_goldberg Apr 13 '18 at 15:03
  • $\begingroup$ @m_goldberg added it. Thanks for the input. $\endgroup$ – henry Apr 14 '18 at 18:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.