[GAP Forum] Create a list of functions in GAP

Robert Morse rm43 at evansville.edu
Wed Sep 11 17:34:58 BST 2013


The value of the variable i is not bound at function definition.
Rather, whatever i 's value at function execution is what is used.

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;

gap> F:=[];
gap> for i in [1..5] do
>       F[i]:=factory(i);
>       od;

Then

gap>F[1](1);
2
gap>F[2](1);
3
gap>F[3](1);
4

Gives what you want.

Robert F. Morse

On Wed, Sep 11, 2013 at 10:21 AM, Le Van Luyen <lvluyen at gmail.com> wrote:
> Dear all,
>
> I want to create a list of functions in GAP and I have used the following
> code lines:
>
> gap> F:=[];
> gap> for i in [1..5] do
>>       F[i]:=function( n)
>>               return n+i;
>>       end;
>>       od;
>
> I expect the result will be: F[1](1)=2; F[2](1)=3; F[3](1)=4
>
> But, In GAP
>
> gap>F[1](1);
> 6
> gap>F[2](1);
> 6
> gap>F[3](1);
> 6
>
>  It looks like all functions of list A are the same.
>
> Could you give me a way to create a list of functions like that?
>
> Thank you very much.
>
> Bests,
>
> Luyen
> _______________________________________________
> Forum mailing list
> Forum at mail.gap-system.org
> http://mail.gap-system.org/mailman/listinfo/forum



More information about the Forum mailing list