[GAP Forum] Argument values in function calls

Laurent Bartholdi laurent.bartholdi at gmail.com
Mon Aug 13 14:27:06 BST 2007


Dear Anvita,
A new variable is allocated in fuction calls, and therefore in Example
2 the variable l is not affected. However, lists are passed by
reference, and not copied; therefore, the contents of l are changed in
Example 1.

Consider Example 1.5:

gap> f1:=function(l)
> l := l+[1];
> return l;
> end;
function( l ) ... end

Then this example behaves just like Example 2.
(I don't think that any programming language would consider copying
lists before passing them to a function; this is usually too expensive
in computational time).

Moral: you may change _l_ without affecting the argument; you may not
change _l's contents_.

Best, Laurent
On 8/13/07, Anvita <anvita21 at gmail.com> wrote:
> Dear Forum,
>
> Could someone please explain to me why in some cases
> a function call may result in a change of the argument's
> value while in others it does not. (See in the two examples below
> the behavior of the value of "a"). The chapter 4.10
> of the manual says that for each argument of a function
> GAP allocates a new variable. Doesn't it mean that
> the initial variable's value should always remain intact?
>
> Thank you,
> Anvita
>
> ### Example 1 ###
>
> gap> f1:=function(l)
> > l[1]:=l[1]+1;
> > return l;
> > end;
> function( l ) ... end
> gap>
> gap> a:=[1];
> [ 1 ]
> gap> b:=f1(a);
> [ 2 ]
> gap> a;
> [ 2 ]
>
> ### Example 2 ###
>
> gap> f2:=function(l)
> > l:=l+1;
> > return l;
> > end;
> function( l ) ... end
> gap>
> gap> a:=1;
> 1
> gap> b:=f2(a);
> 2
> gap> a;
> 1
> -------------------------------
> _______________________________________________
> Forum mailing list
> Forum at mail.gap-system.org
> http://mail.gap-system.org/mailman/listinfo/forum
>


-- 
Laurent Bartholdi          \  laurent.bartholdi<at>gmail<dot>com
EPFL SB SMA IMB MAD         \    Téléphone: +41 21-6935458
Station 8                    \ Secrétaire: +41 21-6935471
CH-1015 Lausanne, Switzerland \      Fax: +41 21-6930339



More information about the Forum mailing list