(sicp18)sicp2.54〜2.56
図形言語で使いたい絵が決まらないので、図形言語のところを飛ばして先に進んでみることにした。
(use pre-sicp) ;;本の内容を写す (define a 1) (define b 2) (list a b) (list 'a 'b) (car '(a b c)) (cdr '(a b c)) ;;memqを作成 (define (memq item x) (cond ((null? x) #f) ((eq? item (car x)) x) (else (memq item (cdr x))))) (memq 'apple '(pear banana prune)) ;; gosh> #f (memq 'apple '(x (apple sauce) y apple pear)) ;; gosh> (apple pear) ;;m2.53 ;;予想?==結果 という感じに書く (list 'a 'b 'c) ;; (a b c)?=gosh> (a b c) (list (list 'george)) ;; ((george))?=gosh> ((george)) (cdr '((x1 x2) (y1 y2))) ;; ((y1 y2))?=gosh> ((y1 y2)) (cadr '((x1 x2) (y1 y2))) ;; (y1 y2)?=gosh> (y1 y2) (pair? (car '(a short list))) ;; #f?=gosh> #f (memq 'red '((red shoes) (blue socks))) ;; #f?=gosh> #f (memq 'red '(red shoes blue socks)) ;; '(red shoes blue socks)?=gosh> (red shoes blue socks) ;;このあたりはとても簡単 ;;m2.54 (define a '(this is a list)) (define b '(this (is a) list)) (equal? a a) ;; gosh> #t (equal? a b) ;; gosh> #f ;;gaucheにequal?が存在したので、名前をsicp-equal?に変える ;;たぶん、問題の通りに実装するとこんな感じ。 (define (sicp-equal? x y) (cond ((and (pair? x) (pair? y)) (and (sicp-equal? (car x) (car y)) (sicp-equal? (cdr x) (cdr y)))) ((and (not (pair? x)) (not (pair? y))) (eq? x y)) (else #f))) ;;naoya-tさんのところからテスト的なものを借りてきてテスト ;;evalの使いかたがあっているか不明>< (for-each (lambda (x) (print "予想は" (car x) " 結果は" (eval (cdr x) interaction-environment) " :" (cdr x))) '((#f sicp-equal? 'a 'b) (#f sicp-equal? 'a 'b) (#f sicp-equal? 'a '(a b)) (#t sicp-equal? '(a b) '(a b)) (#f sicp-equal? '(a a) '(a b)) (#t sicp-equal? '(this is a list) '(this is a list)) (#f sicp-equal? '(this is a list) '(this (is a) list)))) ;; gosh> 予想は#f 結果は#f :(sicp-equal? 'a 'b) ;; 予想は#f 結果は#f :(sicp-equal? 'a 'b) ;; 予想は#f 結果は#f :(sicp-equal? 'a '(a b)) ;; 予想は#t 結果は#t :(sicp-equal? '(a b) '(a b)) ;; 予想は#f 結果は#f :(sicp-equal? '(a a) '(a b)) ;; 予想は#t 結果は#t :(sicp-equal? '(this is a list) '(this is a list)) ;; 予想は#f 結果は#f :(sicp-equal? '(this is a list) '(this (is a) list)) ;;m2.55 ;;分からないので、色々試す。 ;;とりあえず本当にquoteと印字されるか確かめる。 (car ''abracadabra) ;;gosh > quote ;;色々いじってやってみる。 ;;(car '(' abracadabra)) gosh> 'abracadabra ;;(car '') error ;;(car 'abracadabra) not-pair error ;;このどれでもないみたい。 ;;光明が見えた!! ;;gosh> (car 'a'a) ;;*** ERROR: Compile Error: wrong number of arguments: car requires 1, but got 2 ;;"(stdin)":131:(car 'a 'a) ;;つまり、問いの式で評価されているのは (car ' 'abracadabra) ;;これは (car (quote (quote abracadabra))) ;;(quote x)はxを文字列として扱うということなので ;;quoteの第1引数のquoteが取り出されたという感じ…かな?