2.5 Systems with Generic Operations

http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-18.html#%_sec_2.5

この辺からだんだんとひよってくるのを感じる。わからないやつは、SICP Liteのときに取り組もう。

2.5.1 Generic Arithmetic Operations

http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-18.html#%_sec_2.5.1

問題2.77
; (magnitude z)をトレース
(magnitude '(complex rectangular 3 . 4))
(apply-generic 'magnitude '(complex rectangular 3 . 4))
(apply magnitude '(rectangular 3 . 4))
(magnitude '(rectangualr 3 . 4))
(apply-generic 'magnitude '(rectangular 3 . 4))
(apply magnitude '(3 . 4))
(magnitude '(3 . 4))
問題2.78
(define (attach-tag type-tag contents)
  (if (eq? type-tag 'scheme-number) contents
	  (cons type-tag contents)))
(define (type-tag datum)
  (cond ((pair? datum) (car datum))
		((number? datum) 'scheme-number)  ; タグを付ける
		(else (error "Bad tagged datum -- TYPE-TAG" datum))))
(define (contents datum)
  (cond ((pair? datum) (cdr datum))
		((number? datum) datum)
		(else (error "Bad tagged datum -- CONTENTS" datum))))
問題2.79



問題2.80



2.5.2 Combining Data of Different Types

http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-18.html#%_sec_2.5.2

先ほどの節が被演算子が全て同じ型だった場合のケースで、この節では違う型だった場合の取り扱い。
LLをメインに使っているので、型変換とは、かなりプログラミング言語の方にお世話になっている部分だ。

問題2.81

a. apply-genericの無限ループになる。
b. 意味がない
c.

; 型が一致してるにも関わらず、手続きが見つからないので、エラー終了する。
(define (apply-generic op . args)
  (let ((type-tags (map type-tag args)))
	(let ((proc (get op type-tags)))
	  (if proc
	      (apply proc (map contents args))
		  (if (= (length args) 2)
		       (let ((type1 (car type-tags))
			       (type2 (cadr type-tags))
			       (a1 (car args))
			       (a2 (cadr args)))
			  (if (eq? type1 type2)
			       (error "No method for these types"
                               (list op type-tags))
			  (let ((t1->t2 (get-coercion type1 type2))
			          (t2->t1 (get-coercion type2 type1)))
		             (cond (t1->t2
					 (apply-generic op (t1->t2 a1) a2))
					(t2->t1
					 (apply-generic op a1 (t2->t1 a2)))
					(else 
					 (error "No method for these types"
						    (list op type-tags)))))))
	      (error "No method for these types"
			 (list op type-tags)))))))
問題2.82

あとでやる

問題2.83

あとでやる

問題2.84

あとでやる

問題2.85

あとでやる

問題2.86

あとでやる

2.5.3 Example: Symbolic Algebra

http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-18.html#%_sec_2.5.3

全体を飛ばそうwww