TransWikia.com

Return[] being saved to DownValues

Mathematica Asked by Blrp on December 26, 2020

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

3 Answers

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;

Correct answer by Hausdorff on December 26, 2020

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.

Answered by Sjoerd Smit on December 26, 2020

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.

Answered by Carl Woll on December 26, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP