chicken-users
[Top][All Lists]
Advanced

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

Re: [Chicken-users] the effect of set! on the top-level namespace


From: Tobia Conforto
Subject: Re: [Chicken-users] the effect of set! on the top-level namespace
Date: Mon, 15 Oct 2007 19:05:04 +0200
User-agent: Mutt/1.5.11+cvs20060126

Terrence Brannon wrote:
> (set! afunc (lambda (x) (+ x 5)))
> (set! first-func afunc)
> (set! afunc (lambda (x) (* x 1000)))
> (set! second-func afunc)
>
> what is happening to the symbol afunc in line 1 versus line 3.

You might want to think of Scheme values as immutable objects, and of
variables as (mutable) pointers or references to them.  Much like Java
objects (excluding native types) or C pointers, if you have any
experience with them.  Otherwise think of them as links: the variable
contains a link to the value and the value is stored somewhere else.

Line 1 is creating a new immutable lambda object (a function.)
Line 1 is also putting a reference to that object into variable afunc.

Line 2 is copying whatever was in afunc (the reference to the first
function object) into the first-func variable.

Line 3 is creating a new function object and putting a reference to it
into the variable afunc, overwriting what was previouly there (that is,
a reference to the first function object.)

> In particular is the same memory location being over-written?

The memory location of the variable afunc is being overwritten: there is
no more a reference to the first function object, but a reference to the
second one.

> Also, in line 2 is first-func being set to a value which is not
> destroyed by the set! call in line 3?

Yes.  The functions themselves, being immutable and detached from
variables, are not overwritten or modified in any way by set! calls.

> for some code I am writing personally, I have to use set! because
> define inside a let does not seem to affect the top-level the way I
> need it to.

Yes, set! is the preferred operator for changing the value of an
existing variable.  I believe using define with an existing variable
name is not good practice.


Tobia

Note: this might or might not be how Chicken actually handles things
(probably not, I dunno) it's just a very introductory answer to a
generic Scheme question.




reply via email to

[Prev in Thread] Current Thread [Next in Thread]