LoginSignup
1
1

More than 5 years have passed since last update.

オンラインSICP読書女子会 #25 (2.3.1)

Last updated at Posted at 2016-11-09

オンラインSICP読書女子会 #25 (2.3.1)

練習問題 2.53 - 2.55

2.3 記号データ

2.3.1 クォート

シンボル値的なもの.
atom とも言ったような?

gosh> (define a 1)
a
gosh> (define b 2)
b
gosh> (list a b)
(1 2)
gosh> (list 'a 'b)
(a b)
gosh> (list 'a b)
(a 2)

リストに適用するとリストの全部の要素が全部 quote される:

gosh> (car '(a b c))
a
gosh> (cdr '(a b c))
(b c)
gosh> '(a 1 (b 2))
(a 1 (b 2))

memq の定義でしれっと false っていう定数使ってるけれど gosh さんにはこれない… #f だし….

(define (memq item x)
    (cond
        ((null? x) #f)
        ((eq? item (car x)) x)
        (else (memq item (cdr x)))))

ところで memq ってなんの略? member query? =ω=;

追記: Scheme 標準だったぽい…! Function: memq obj list

memqは同一性の判定にeq?を、memvはeqv?を、 memberはequal?を使います。

なるほど??
[mem]ber by [q] (=eq?) ってことかな?=ω=;

ex-2.53. quote あれこれお試し

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

ex-2.54. equal?

(define (equal? a b)
    (cond
        ((eq? a b) #t)
        ((and (null? a) (null? b)) #t)
        ((or (null? a) (null? b)) #f)
        ((and (pair? a) (pair? b)) 
            (and (equal? (car a) (car b)) (equal? (cdr a) (cdr b))))
        (else #f)))
gosh> (equal? 'a 'a)
#t
gosh> (equal? 'a 'b)
#f

gosh> (equal? '() '())
#t
gosh> (equal? '(a) '())
#f
gosh> (equal? '() '(a))
#f
gosh> (equal? '(a) '(a))
#t

gosh> (equal? '(a) '(b))
#f

追記: (eq? '() '()) は真になる模様. これもシンボル値…?
cond の2行目の判定はこれにマッチするのでなくてよかった模様.

空リストって pair の一種にはならないのね…!(・ω・;

gosh> (pair? ())
#f

; おまけ (Erlang の場合).
erl> is_list([]).
true

修正版:

(define (equal? a b)
    (cond
        ((eq? a b) #t)
        ((or (null? a) (null? b)) #f)
        ((and (pair? a) (pair? b)) 
            (and (equal? (car a) (car b)) (equal? (cdr a) (cdr b))))
        (else #f)))

(最後に (else #f) ってなるの前の条件句と混ぜちゃいたさ少しあるけれど, 可読性がとても落ちそうなのでこのままのほうがよさそう.)

ex-2.55. (car ''abracadabra)

ダブルクォートっぽいけどシングルクォート2つ>ω<

p.153 脚注 34 によると, '(a b c)(quote a b c) という特殊形式の syntax sugar になっている.
これに当てはめると,

(car ''abracadabra)
(car '(quote abracadabra))

であり, (car '(a b c))a となるのと同様に (car '(quote abracadabra))quote となる.

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1