Bill Allombert on Sat, 14 Jun 2014 22:28:08 +0200


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: recursive inline functions


On Sat, Jun 14, 2014 at 12:16:45AM -0400, Max Alekseyev wrote:
> Hello!
> 
> Is this an expected behavior?
> 
> ? inline(f)
> ? f(n) = if(n>1,n*f(n-1),1)
> %2 = (n)->my(f=0);if(n>1,n*f(n-1),1)
> ? f(10)
>   ***   at top-level: f(10)
>   ***                 ^-----
>   ***   in function f: if(n>1,n*f(n-1),1)
>   ***                           ^---------
>   ***   not a function in function call
>   ***   Break loop: type 'break' to go back to GP prompt

Alas yes. It is a known design issue of the syntax for defining anonymous
closure: it is not possible to create recursive anonymous closures.

See 
<http://pari.math.u-bordeaux.fr/archives/pari-dev-0710/msg00010.html>

However there is a universal work around: the Y combinator:
<http://pari.math.u-bordeaux.fr/archives/pari-dev-1401/msg00012.html>

Try

my(Y=f->x->f(f,x), g(fun,x)=if(x==0,1,x*fun(fun,x-1)), fact=Y(g)); fact(10)

So maybe I should implement self().

Cheers,
Bill.