続2・PrologでR6RS ~call/ccの巻~

わーい \(^o^)/ Prologで書いたSchemeインタプリタにcall/ccが付いたよー!

?- eval_step([store,[], [+, [call_cc, [lambda,[k], [k,99], 1 ]], 1] ], X).
[store, [], [[lambda, [#:G1716], [+, #:G1716, 1]],
[call_cc, [lambda, [k], [k, 99], 1]]]]
[store, [], [[lambda, [#:G1716], [+, #:G1716, 1]],
[[lambda, [k], [k, 99], 1],
[throw, #:G1730, [[lambda, [#:G1716], [+, #:G1716, 1]], #:G1730]]]]]
[store, [], [[lambda, [#:G1716], [+, #:G1716, 1]],
[[lambda, [], [[throw, #:G1730, [[lambda, [#:G1716], [+, #:G1716, 1]], #:G1730]], 99], 1]]]]
[store, [], [[lambda, [#:G1716], [+, #:G1716, 1]],
[begin, [[throw, #:G1730, [[lambda, [#:G1716], [+, #:G1716, 1]], #:G1730]], 99], 1]]]
[store, [], [[lambda, [#:G1716], [+, #:G1716, 1]], [values, 99]]]
[store, [], [[lambda, [#:G1716], [+, #:G1716, 1]], 99]]
[store, [], [[lambda, [], [+, 99, 1]]]]
[store, [], [begin, [+, 99, 1]]]
[store, [], [+, 99, 1]]
[store, [], 100]
[store, [], [values, 100]]
X = [store, [], [values, 100]] ;
No

式”(+ (call/cc (lambda (k) (k 99) 1)) 1)”の評価を行っています。
注目すべきは2ステップ目。
call/ccによって継続オブジェクトが作られていますが、
その内容は「何かを受け取って1を足す “(lambda (#:G1716) (+ #:G1716 1))”」であり、
これはまさに最初の式のcall/ccの箇所を別のものに変えた関数です。
見事なまでに現在の継続が作られています。
あとはdynamic-windの規則を作れば完全なcall/ccとなるはずです。

Leave a Reply