sicp每日一題[2.53-2.55]

再思即可發表於2024-10-23

2.53不用寫程式碼,2.54和2.55屬於一道題,所以就放到一起吧

Exercise2.53

What would the interpreter print in response to evaluating each of the following expressions?

(list 'a 'b 'c)
(list (list 'george))
(cdr '((x1 x2) (y1 y2)))
(cadr '((x1 x2) (y1 y2)))
(pair? (car '(a short list)))
(memq 'red '((red shoes) (blue socks)))
(memq 'red '(red shoes blue socks))

結果如下:

'(a b c)
'((george))
'((y1 y2))
'(y1 y2)
#f
#f
'(red shoes blue socks)

Exercise 2.54

Two lists are said to be equal? if they contain equal elements arranged in the same order. For example,

(equal? '(this is a list) '(this is a list))

is true, but

(equal? '(this is a list) '(this (is a) list))

is false. To be more precise, we can define equal? recursively in terms of the basic eq? equality of symbols by saying that a and b are equal? if they are both symbols and
the symbols are eq?, or if they are both lists such that (car a) is equal? to (car b) and (cdr a) is equal? to (cdr b). Using this idea, implement equal? as a procedure.


這道題挺簡單的,依次比較就行了。

(define (equal? a b)
  (cond ((and (null? a) (null? b)) true)
        ((or (null? a) (null? b)) false)
        ((eq? (car a) (car b)) (equal? (cdr a) (cdr b)))
        (else false)))


(equal? '(this is a list) '(this is a list))
(equal? '(this is a list) '(this (is a) list))

; 執行結果
#t
#f

Exercise 2.55

Eva Lu Ator types to the interpreter the expression

(car ''abracadabra)

To her surprise, the interpreter prints back quote. Explain.


因為 (car ''abracadabra) 被直譯器理解為 (car (quote (quote abracadabra))),第一個 quote 引用了後面的內容 (quote abracadabra)
這實際上是一個有2個元素的 list,對這個list 呼叫 car 就取出了第一個元素 quote。也就是第二個 quote 沒有被當作函式使用,而是被當作字串了。

相關文章