I try to figure out something intersting that happen in Scheme:
(define last-pair
(lambda (x)
(if (null? (cdr x))
x
(last-pair (cdr x)))))
When I defined foo in this way:
(define foo
(lambda ()
(let ((s (list 'he 'said:)))
(set-cdr! (last-pair s)
(list 'ha 'ha))
s)))
and run foo 3 times, I got:
(he said: ha ha)
(he said: ha ha)
(he said: ha ha)
But when I defined foo in this way:
(define foo
(lambda ()
(let ((s '(he said:)))
(set-cdr! (last-pair s)
(list 'ha 'ha))
s)))
and run foo 3 times, I got:
(he said: ha ha)
(he said: ha ha ha ha)
(he said: ha ha ha ha ha ha)
But why? My first thought was that we build always new list in the first foo
, and in the second we don't. But I didn't understood how it actully working. Scheme define adress in the second foo
, and do what? Is it define as a list also in the second foo? or a symbol?
Thanks.
mlist
for creating mutable lists, as the '(a b c) syntax produces immutable lists – Óscar López