gencomp 確認 (4)
SICP にこれと同じような課題が最後にあったような気が。
それは良いとして (何
色々確認しないとイケないコトが満載でメモを取らずにだらだら読むと微妙。しかも gauche 特有のナニに慣れてない部分があったりして読むスピード的にストレスフル。
とりあえず
未だに直感的に理解できてないナニを以下に。
port-fold とか
以下なカンジのソレがあって
(with-input-from-file src (lambda () (emit-toplevel-executor (reverse (port-fold compile-toplevel-form '() read)))))
ええと、gencomp 内で M-x occur したら以下な出力
4 matches for "compile-toplevel-form" in buffer: gencomp 141: (reverse (port-fold compile-toplevel-form '() read))))) 203:(define (compile-toplevel-form form seed) 213: (fold compile-toplevel-form seed body))) 264: (compile-toplevel-form `(define ,name (lambda ,args ,@body)) seed))
fold も微妙なんだけどなぁ、と言いつつプログラミング Gaucheの p.46 あたりのアレをナニ。
リストの要素を順に処理して行く手続きの基本になるのは fold です。
(fold <手続き> <初期値> <リスト>)
あと、テキストによれば fold 系の手続きに渡される引数は
- 最初の引数はリストの要素
- 次の引数は積み上がってる戻り
何が微妙かというと上記 compile-toplevel-form で言うと
- 引数に何が渡されるのかイメージできず
- 何を戻せばええのかイメージできず
というナニ。仕方が無いので SICP 持ってきて accumulate なソレを確認。でも fold と SICP の accumulate は違うんかいな。確認。
gosh> (fold cons '() (list 1 2 3 4 5)) (5 4 3 2 1) gosh> (define (accumulate op init seq) (if (null? seq) init (op (car seq) (accumulate op init (cdr seq))))) accumulate gosh> (accumulate cons '() (list 1 2 3 4 5)) (1 2 3 4 5) gosh>
わはは。Gauche 本だと fold は
(cons 5 (cons 4 (cons 3 (cons 2 (cons 1 '())))))
との事。上記の accumulate は逆ですな
(cons 1 (cons 2 (cons 3 (cons 4 (cons 5 '())))))
だから何だ、というワケではないんですが、fold は繰り返しで accumulate は再帰なのか。どう書いてるのか、という方面にトウヒしそうなので、そちらはスルー。
と言いつつ書いてみた。
(define (myfold op init seq) (if (null? seq) init (myfold op (op (car seq) init) (cdr seq))))
.txt な emacs で書いたんで tab が微妙。trace してないんですが、これは繰り返しになってるはず。
てーコトは
141: (reverse (port-fold compile-toplevel-form '() read))))) 203:(define (compile-toplevel-form form seed)
なソレ的には
- 141 だと
- init は '() で
- seq は read で読み込まれたソレ
- 203 だと
- form に渡されるのは car 要素
- seed に渡されるのは積み上がるナニ
- 戻す値は port-fold の第二引数に積まれてく
という事?
むむ
とりあえず作文に時間がかかってます。割り込み入れつつ色々見てて
- 0.8.14 の gencomp 見易い
- lib/gauche/cgen.scm のコメントなんとなく意味判りつつある
とか
- compile-toplevel-form 手続きのコメントもちゃんと読まなきゃ
とか
ただ
cgen.scm のコメントとか入出力なアレとか見てなんとなく流れは分かりつつあるんですが、具体的な部分が微妙っちゃ微妙。