Why doesn't this code work on Scheme?

 (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've tried running them in DrScheme and they don't work. Why?

+1


source to share


3 answers


Think of the multitude! is a special form of type define that does not evaluate its first operand. You are telling the schema interpreter to set this variable exactly as you write it. In your example, it will not evaluate the expression "a" against the word a. Instead, it will look for the binding of a variable named "a" (or, depending on your interpreter, it might just break before that, 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 exactly like any circuit function in which it evaluates all of its operands. It takes two values, a pair and some schema value, and mutates the pair so that the car now points to the schema value.



So for example.

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

      

+3


source


Because the first argument to set! it's a variable name, not an "lvalue" so to speak.



In the latter case, use (set-car! A 10).

+2


source


The problem is with (set! 'A 10), since you shouldn't specify the character a.

It looks like you are trying to learn Scheme and you don't know Lisp, huh? If so, I highly recommend trying Clojure as it is easier to learn Lisp. I was unable to understand the interactions between reader, score, symbols, special forms, macros, etc. In both Common Lisp and Scheme, because it all seemed to interact in a confusing way, but I finally really understand them in Clojure. Even though this is new, I found Clojure's documentation to be actually clearer than anything I have found for Scheme or CL. Start with a video at http://clojure.blip.tv/ and then read the docs at Clojure.org.

-2


source







All Articles