問題2.20 ドット末尾記法
(define (copy items condition) (if (null? items) items (if (condition (car items)) (cons (car items) (copy (cdr items) condition)) (copy (cdr items) condition)))) (define (same-parity . items) (copy items (if (even? (car items)) even? odd?)))
汎用の条件式を取れるcopyを作成しておいて、same-parity用の条件をcopyに渡すようにしてみた。
最初自分では、
(define (get-condition-of-same-parity items) (if (even? (car items)) (lambda (n) (even? n)) (lambda (n) (not (even? n))))) (define (same-parity . items) (print items) (copy items (get-condition-of-same-parity items)))
なんてのの作ってたけど、ここ見てみたら
(if (even? (car items)) even? odd?)
って、全然シンプルに解決できる事がわかった。基本関数をそのまま返すって言う発想がまだ無いんだろうな。
まだまだ修行が足りないようで。
脚注11
それから、脚注11のドット末尾記法のlambdaでの定義方法だけど、
(define (f1 x y . z) (print x) (print y) (print z)) (define f2 (lambda (x y . z) (print x) (print y) (print z))) (define (g1 . w) (print w)) (define g2 (lambda w (print w)))
f1とf2が同じだってのはわかるけど、g1とg2が同じというのがよくわからない。
そもそも引数をカッコ無しで受け取る
(lambda w (print w))
ってのが初めて見る形のような気が。
どこか読み飛ばしたかな。
(11/13 追記: (w) のカッコを省略してwになってるだけじゃん。何混乱してたんだろう。)
(11/13 追記2: と思って実際確かめてみたら、なんと、カッコ無しの仮引数は複数の引数を受け取ってリストとして保持する機能を持っている事がわかった。
例えば、
((lambda x x) 1 2 3 4)
で、(1 2 3 4) が評価値として帰るのだ。う〜む。まだまだ知らない事ばかりです。