tags:

views:

206

answers:

3
 (define a 42)
 (set! 'a 10)


(define a 42)
(define (symbol) 'a)
(set! (symbol) 10)


(define a (cons 1 2))
(set! (car a) 10)

I tried running them in DrScheme and they don't work. Why?

+2  A: 

Because the first argument of set! is a variable name, not an "lvalue", so to speak.

For the last case, use (set-car! a 10).

sanxiyn
+3  A: 

Think of set! is a special form like define which does not evaluate its first operand. You are telling the scheme interpreter to set that variable exactly how you write it. In your example, it will not evaluate the expression 'a to the word a. Instead, it will look for a variable binding named "'a" (or depending on your interpreter might just break before then since I think 'a is not a valid binding).

For the last set of expressions, if you want to set the car of a pair, use the function (set-car! pair val) which works just like any scheme function in that it evaluates all of its operands. It takes in two values, a pair and some scheme value, and mutates the pair so that the car is now pointing to the scheme value.

So for example.

>(define pair (cons 1 2))
>pair
(1 . 2)
>(set-car! pair 3)
(3 . 2)
mweiss
A: 

The issue is with (set! 'a 10), as you shouldn't be quoting the symbol a.

It sounds like you're trying to learn Scheme, and you don't know Lisp, yes? If so, I strongly recommend trying Clojure as an easier to learn Lisp. I failed to grasp the interaction between the reader, evaluation, symbols, special forms, macros, and so forth in both Common Lisp and Scheme because those things all seemed to interact in tangled ways, but I finally really understand them in Clojure. Even though it's new, I found Clojure documentation is actually clearer than anything I found for Scheme or CL. Start with the videos at http://clojure.blip.tv/ and then read the docs at clojure.org.

Jegschemesch