Reputation: 1276
I'm a bit confused on how to append a list that I've gotten from the assoc
procedure into another list, here is what I have:
(define new-list (list 'test))
(define source-a (list '(a foo) '(b bar) '(c hello)))
(append new-list (assoc 'a source-a))
(display new-list)
The output is just (test)
and I'm not sure why it's not (test a foo)
. Is it possible to append like this?
Upvotes: 0
Views: 84
Reputation: 43852
That's because append
is not a mutating function. It returns a new list with its arguments appended together. By convention in Scheme, functions that perform mutation end with an exclamation mark, such as set!
.
You can use set!
to modify new-list
so that it is updated, like this:
(set! new-list (append new-list (assoc 'a source-a)))
However, this is highly discouraged in Scheme. While imperative programming makes heavy use of mutation, functional programming languages (including Scheme) try to avoid mutation and side-effects, since those can make programs harder to reason about.
Ideally, you'd just declare a new binding with the new value instead of updating an existing binding. Something like this would work just fine:
(define original-list (list 'test))
(define source-a (list '(a foo) '(b bar) '(c hello)))
(define new-list (append original-list (assoc 'a source-a)))
(display new-list)
Upvotes: 2