3
$\begingroup$

Example:

f[x_] := f[x] = (If[x < 0, Return[x]]; x)
f[1];
f[-5];
DownValues[f][[1 ;; 2]]

(* {HoldPattern[f[-5]] :> Return[-5], HoldPattern[f[1]] :> 1} *)

I want it to save the value that is returned, without the Return[]. In case it matters, the actual function looks something like this:

f[list_,n_] := f[list,n] = Block[{li = list, moreVars},
    Which[
        n == 0, Return@li,
        li[[i1]] > 0, li[[i1]]--,
        li[[i2]] > 0, li[[i2]]--,
        True, Return@li
    ];
    f[li, n - If[bla, 2, 1]]
]
$\endgroup$

3 Answers 3

1
$\begingroup$

It is not very fancy, but you could just use a replacement:

f[x_] := f[x] = (If[x < 0, Return[x]]; x) /. Return[z_] :> z
f[1]; f[-5];
DownValues[f][[1 ;; 2]]
{HoldPattern[f[-5]] :> -5, HoldPattern[f[1]] :> 1}

Alternatively you could perhaps get rid of Return altogether. For example,

f[list_, n_] := f[list, n] =
  Block[{li = list, moreVars},
   Which[
    n == 0,
        li,
    li[[i1]] > 0,
        li[[i1]]--;
        f[li, n - If[bla, 2, 1]],
    li[[i2]] > 0,
        li[[i2]]--;
        f[li, n - If[bla, 2, 1]],
    True,
        li]
   ]

or in a more functional approach

f[list_, n_] /; n == 0 := f[list, n] = list;

f[list_, n_] /; list[[i1]] > 0 := f[list, n] = 
   Block[{li = list, moreVars},
    li[[i1]]--;
    f[li, n - If[bla, 2, 1]]
    ];

f[list_, n_] /; list[[i2]] > 0 := f[list, n] = 
   Block[{li = list, moreVars},
    li[[i2]]--;
    f[li, n - If[bla, 2, 1]]
    ];

f[list_, n_] := f[list, n] = list;
$\endgroup$
2
$\begingroup$

You could use the two-arg version of Return:

Clear[f]

f[x_] := f[x] = (If[x<0, Return[x, CompoundExpression]];x)
f[1];
f[-5];
DownValues[f][[1;;2]]

{HoldPattern[f[-5]] :> -5, HoldPattern[f[1]] :> 1}

The problem with single-arg Return is that heuristics must be used to determine what construct is being returned from.

$\endgroup$
1
$\begingroup$

In this case, I think Throw and Catch are probably better constructs for what you want to do:

f[list_,n_] := f[list,n] = Catch @ Block[{li = list, moreVars},
    Which[
        n == 0, Throw[li],
        li[[i1]] > 0, li[[i1]]--,
        li[[i2]] > 0, li[[i2]]--,
        True, Throw[li]
    ];
    f[li, n - If[bla, 2, 1]]
]

This gives you much better control over the program flow than Return.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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