0

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?

MannfromReno
  • 1,276
  • 1
  • 14
  • 32

1 Answers1

2

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)
Alexis King
  • 43,109
  • 15
  • 131
  • 205
  • Ah, that makes sense now! I'm still new to Scheme and trying to wrap my head around all of it. – MannfromReno Mar 10 '15 at 12:41
  • 2
    @MannfromReno While the common patterns may be different, do note that there's nothing unique to Scheme here. In C or Java, etc., the same thing applies. E.g., if you write `int square( int x ) { return x*x; }`, and then do `int a = 4; square(a); print(a);`, you'll see `4`, not `16`. You'd need to do same thing that you could do in Scheme: `int a = 4; a = square(a); print(a);`. There's nothing special about Scheme in this regard. – Joshua Taylor Mar 10 '15 at 17:30
  • Yeah you're right, when passing by value the value will obviously not change. I guess one of those stupid moments when I was just hacking at the keys. Thanks for clarification. – MannfromReno Mar 10 '15 at 20:25