8

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}

james
  • 3,043
  • 13
  • 29

2 Answers2

9

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.

Chris Degnen
  • 30,927
  • 2
  • 54
  • 108
  • 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
  • How do you index the returned list later? whenever I try running test[5][[0]] I get List as output... – gen Feb 06 '21 at 01:38
  • @gen In Mathematica lists are one-indexed, so they begin at 1. So you can use 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". – Chris Degnen Feb 06 '21 at 10:29
4

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}];
henry
  • 2,510
  • 14
  • 28