Memoized recursive functions. How to make them fool-proof?

前端 未结 2 1162
星月不相逢
星月不相逢 2021-02-13 10:22

Memoized functions are functions which remember values they have found. Look in the doc center for some background on this in Mathematica, if necessary.

Suppose you have

2条回答
  •  南方客
    南方客 (楼主)
    2021-02-13 10:44

    A slight modification on Leonid's code. I guess I should post it as a comment, but the lack of comment formatting makes it impossible.

    Self adaptive Recursion Limit

    Clear[f];
    $RecursionLimit = 20;
    Module[{ff},
     ff[0] = ff[1] = 1;
     ff[x_] := 
      ff[x] = Block[{$RecursionLimit = $RecursionLimit + 2},  ff[x - 1] + ff[x - 2]];
     f[x_Integer] := f[x] = ff[x]]
    
    f[30]
    (*
    -> 1346269
    *)
    
    $RecursionLimit
    (*
    -> 20
    *)
    

    Edit

    Trying to set $RecursionLimit sparsely:

    Clear[f];
    $RecursionLimit = 20;
    Module[{ff}, ff[0] = ff[1] = 1;
     ff[x_] := ff[x] =
       Block[{$RecursionLimit =
          If[Length@Stack[] > $RecursionLimit - 5, $RecursionLimit + 5, $RecursionLimit]}, 
           ff[x - 1] + ff[x - 2]];
     f[x_Integer] := f[x] = ff[x]]  
    

    Not sure how useful it is ...

提交回复
热议问题