問題2-53〜55
約二ヶ月間、SICPから離れてしまいましたが、今日から徐々に再開していきたいと思います。手始めに第一章から第三章までを流し読みしました。二章の後半から三章にかけての部分は、今回初めて触れる内容でしたが、非常に面白そうな感触を受けることができ、早く問題を解きたいという気分にさせられました。というわけで、第二章の図形問題の部分を飛ばして、「記号データ」の部分から問題を解いていきます。
まずは、問題2-53です。
(define (memq item x) (cond ((null? x) #f) ((eq? item (car x)) x) (else (memq item (cdr x))))) (list 'a 'b 'c) ;=>(a b c) (list (list 'george)) ;=>((george)) (cdr '((x1 x2) (y1 y2))) ;=>((y1 y2)) (cadr '((x1 x2) (y1 y2))) ;=>(y1 y2) (car '(a short list)) ;=>a (pair? (car '(a short list))) ;=>#f (memq 'red '((red shoes) (blue socks))) ;=>#f (memq 'red '(red shoes blue socks)) ;=>(red shoes blue socks)
次の問題2-54は、リストの要素が完全に一致するかを調べるequal?手続きです。
(define (equal? list1 list2) (cond ((and (null? list1) (null? list2)) #t) ((or (null? list1) (null? list2)) #f) ((eq? (car list1) (car list2)) (equal? (cdr list1) (cdr list2))) (else #f))) (equal? '(this is a list) '(this is a list)) ;=> #t (equal? '(this is a list) '(this (is a) list)) ;=>#f (equal? '(this is a list) '(this is a list for lisp)) ;=>#f
今日の最後、問題2-55は、注釈34に書いてあることの確認です。
(car ''abracadabra) ;=>quote (car (quote (quote abracadabra))) ;=>quote