[GAP Forum] Create a list of functions in GAP

Robert Morse rm43 at evansville.edu
Wed Sep 11 22:35:51 BST 2013


All free variables in a GAP function have a static binding within its
lexicographical closure.  In the original program the same i is a free
variable in each function and the lexicographical closure is global
name space. Hence any modification of i changes all the function
definitions.

factory := function(i) local f; f := function(n) return n+i; end;
i:=5; return f; end;

The lexicographical closure of the variable i is the factory function
definition.  Since i is free in f and the last assignment is within
the lexicographical closure of i we have changed the function
definition.

f1 := factory(1);  f2:=factory(2);

f1(1)  ---> returns 6
f2(1)  ---> returns 6

In the example I gave before and

F := List([1..5], i -> (n -> n + i));

we lose access to the lexicographic scope of i and the values are
fixed as desired.


Robert F. Morse



On Wed, Sep 11, 2013 at 3:10 PM, Bill Allombert
<Bill.Allombert at math.u-bordeaux1.fr> wrote:
> On Wed, Sep 11, 2013 at 11:34:58AM -0500, Robert Morse wrote:
>> The value of the variable i is not bound at function definition.
>> Rather, whatever i 's value at function execution is what is used.
>
> Please excuse my curiosity as someone who wrote some computer algebra system
> interpretor.
> Are you saying that i is a global variable which is dynamicaly scoped ?
>
>> After the loop the variable i has the value 5.  Hence calling each
>> instance F[i] returns the same value.
>>
>> You can accomplish what you want by writing a function that creates
>> the function (binding the value i):
>>
>> factory := function(i) return function(n) return n+i; end; end;
>
> and there i is function parameter which is lexicaly scoped,
> and functions are closed over lexicaly scoped variable ?
>
> Cheers,
> Bill.
>
> _______________________________________________
> Forum mailing list
> Forum at mail.gap-system.org
> http://mail.gap-system.org/mailman/listinfo/forum



More information about the Forum mailing list