problem with recursive functions



On 10/6/06, Norber Vegh <jack at omega.telia.net> wrote:

> f[1] : lambda( [x], makelist( i, i, 1, x ) );
> f[d] := lambda( [x], 2*f[d-1](x) );
>
> Then f[1](8) will create a list with 8 elements, however f[2](8) will not work.
> Why is that?

The body of a lambda expression is not evaluated; it is not even simplified
(so stuff like 1 + 1 appears verbatim in a lambda expression).
As noted by Stavros it is necessary to substitute d - 1 into the
lambda expression to get the hoped-for result. Here is another
version. I like buildq better than subst in this context because
buildq does not evaluate its arguments. Also buildq makes
substitutions in parallel (although that is not relevant here).

f[d] := if d=1 then lambda ([x], makelist (i, i, 1, x))
           else buildq ([d1 : d - 1], lambda ([x], 2 * f[d1](x)));

f[4](8);
 => [8,16,24,32,40,48,56,64]

arrayinfo (f);    /* show list of cached indices */
 => [hashed,1,[1],[2],[3],[4]]

listarray (f);    /* show list of cached values */
 => [lambda([x],makelist(i,i,1,x)),
       lambda([x],2*f[1](x)),
       lambda([x],2*f[2](x)),
       lambda([x],2*f[3](x))]


HTH
Robert Dodier