本節實現了amb求值器,題目都是擴充套件這個求值器,引入一些特殊的過程。我的嘗試解答從4.51開始
習題4.51,要求實現permanent-set!,這個過程的***在遇到失敗時不撤銷,實現如下:
;擴充analyze
((permanent
-assignment? exp)
(analyze
-permanent
-assignment exp))
;實現(define (permanent
-assignment? exp)
(tagged
-list? exp
'permanent-set!))
(define (analyze
-permanent
-assignment exp)
(let ((var (assignment
-variable exp))
(vproc (analyze (assignment
-value exp))))
(lambda
(env succeed fail)
(vproc env
(lambda
(val fail2)
(set
-variable
-value! var val env)
(succeed
'ok fail2))
fail))))
習題4.52,實現if-fail的特殊形式,在第乙個表示式如果求值成功,就返回該表示式的值,否則返回第二個表示式的值,實現如下:
;擴充analyze
((if
-fail? exp)
(analyze-if
-fail exp))
;實現(define (if-
fail? exp)
(tagged
-list? exp
'if-fail))
(define (analyze-if
-fail exp)
(let ((pproc (analyze (if-
predicate exp)))
(cproc (analyze (if-
consequent exp))))
(lambda
(env succeed fail)
(pproc env (
lambda
(pred
-value fail2)
(succeed pred
-value fail2))
(lambda
() (cproc env succeed fail))))))
pproc如果執行成功,就返回結果pred-value,否則就執行fail過程
(lambda
() (cproc env succeed fail)),測試略。
習題4.53,根據題意可知這個過程返回結果應該是(prime-sum-pair '(1 3 5 8) '(20 35 110))的所有結果,執行也是如此:
;;; amb
-eval value:((8
35) (
3110
) (3
20))
習題4.54,將require實現為特殊形式:
;擴充analyze
((require? exp)
(analyze
-require exp))
;實現(define (require? exp)
(tagged
-list? exp
'require))
(define (require
-predicate exp)
(cadr exp))
(define (analyze
-require exp)
(let ((pproc (analyze (require
-predicate exp))))
(lambda
(env succeed fail)
(pproc env (
lambda
(pred
-value fail2)(if
(not
pred
-value)
(fail2)
(succeed
'ok fail2)))
fail))))
文章**莊周夢蝶 ,原文發布時間2008-11-21
sicp 4 2 2小節部分習題
4.27,l eval input define count 0 l eval value ok l eval input define id x set count 1 count x l eval value ok l eval input define w id id 10 l eval va...
sicp 4 2 2小節部分習題
4.27,l eval input define count 0 l eval value ok l eval input define id x set count 1 count x l eval value ok l eval input define w id id 10 l eval va...
sicp 3 1 1小節習題嘗試解答
這一節主要是介紹區域性狀態變數,介紹了set 和begin的語法,看來ruby使用 號來表示改變變數值不是什麼新鮮主意。習題3.1,不解釋了 習題3.1 define make accumulator init define accumulator num set init init num ini...