Add exercise 4.51

This commit is contained in:
Oliver Payne 2024-01-30 19:41:57 +00:00
parent 3632855fe5
commit 174d563782
3 changed files with 55 additions and 0 deletions

View File

@ -352,3 +352,42 @@ try-again
(compound-sentence (compound-sentence (compound-sentence (compound-sentence (simple-sentence (simple-noun-phrase (article the) ((noun professor))) (verb studies)) (connective and) (simple-sentence (simple-noun-phrase (article a) ((noun cat))) (verb studies))) (connective and) (simple-sentence (simple-noun-phrase (article the) ((noun professor))) (verb studies))) (connective and) (simple-sentence (simple-noun-phrase (article the) ((noun cat))) (verb sleeps))) (connective and) (simple-sentence (simple-noun-phrase (article the) ((noun student))) (verb studies)))
;;; Amb-Eval input:
;; Exercise 4.51:
;;; Amb-Eval input:
(define count 0)
(let ((x (an-element-of '(a b c)))
(y (an-element-of '(a b c))))
(permanent-set! count (+ count 1))
(require (not (eq? x y)))
(list x y count))
;;; Starting a new problem
;;; Amb-Eval value:
0
ok
;;; Amb-Eval input:
;;; Starting a new problem
;;; Amb-Eval value:
0
(a b 2)
;;; Amb-Eval input:
try-again
;;; Amb-Eval value:
3
(a c 3)
;; Using set! instead of permanent-set! resets the counter back to 0
;; on each backtrack of x or y, so will always be 1.

View File

@ -29,6 +29,7 @@
((quoted? exp) (analyze-quoted exp))
((variable? exp) (analyze-variable exp))
((assignment? exp) (analyze-assignment exp))
((permanent-assignment? exp) (analyze-permanent-assignment exp))
((definition? exp) (analyze-definition exp))
((if? exp) (analyze-if exp))
((lambda? exp) (analyze-lambda exp))
@ -132,6 +133,19 @@
(fail2)))))
fail))))
(define (analyze-permanent-assignment exp)
(let ((var (assignment-variable exp))
(vproc (analyze (assignment-value exp))))
(lambda (env succeed fail)
(vproc env
(lambda (val fail2) ; *1*
(let ((old-value
(lookup-variable-value var env)))
(set-variable-value! var val env)
(succeed 'ok
fail2)))
fail))))
;;;Procedure applications
(define (analyze-application exp)

View File

@ -83,6 +83,8 @@
;; Assignment
(define (assignment? exp)
(tagged-list? exp 'set!))
(define (permanent-assignment? exp)
(tagged-list? exp 'permanent-set!))
(define (assignment-variable exp) (cadr exp))
(define (assignment-value exp) (caddr exp))
(define (make-assignment variable value)