Karim Belabas on Fri, 22 Aug 2014 18:16:01 +0200


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

Re: Syntax for inner function


* Josef Eschgfaeller [2014-08-22 17:24]:
> T (a,v) = apply(i->v[i+1],a)
> 
> a=[0,1,1,0,0,1]; v=[8,9]
> w=T(a,v); print(w) \\ [8, 9, 9, 8, 8, 9]
> 
> S (a,v) = {my (t);
> t(i)=v[i+1]; apply(t,a)}
> 
> w=S(a,v); print(w)
> \\ (i)->my(a=[0, 1, 1, 0, 0, 1],v=[8, 9],t=0);v[i+1];apply(t,a)
> 
> S should do the same thing as T.
> What is wrong?

This is discussed in "2.7.6 Defining functions within a function" in GP
user's manual. The parser sees

  'v[i+1]; apply(t,a)'

as the definition of t(i) (indeed, everything between 't(i)=' and the
end of the expression).

> Is it possible to define an inner function t?

Use parentheses for grouping:

  S(a,v) = {
    my(t);
    (t(i) = v[i+1]);   \\ note the "extra" parentheses
    apply(t,a)
  }

or simply

  S(a,v) = {
    my (t(i) = v[i+1]);
    apply(t,a)
  }

In this case, an anonymous closure is even simpler, you don't actually
need to bind it to a name:

  S(a,v) = apply(i->v[i+1], a)

Cheers,

    K.B.
--
Karim Belabas, IMB (UMR 5251)  Tel: (+33) (0)5 40 00 26 17
Universite de Bordeaux         Fax: (+33) (0)5 40 00 69 50
351, cours de la Liberation    http://www.math.u-bordeaux1.fr/~kbelabas/
F-33405 Talence (France)       http://pari.math.u-bordeaux1.fr/  [PARI/GP]
`