Compare commits

...

2 Commits

Author SHA1 Message Date
Oliver Payne 34400a1bc4 Add amb utilities that are loaded at startup 2023-11-01 22:50:31 +00:00
Oliver Payne f769d990ec Add exercise 4.37 2023-11-01 22:41:55 +00:00
3 changed files with 48 additions and 1 deletions

View File

@ -54,3 +54,19 @@
(define (a-triple-with-sum-from n)
(amb (a-triple-with-sum-between n (+ n 1))
(a-triple-with-sum-from (+ n 1))))
;; Exercise 4.37
;; Alternative version from the book. I think this will be more
;; efficient because it only has to explore the values of k that are
;; sums of the squares of i and j, rather than all integers from j up
;; to high.
(define (a-pythagorean-triple-between* low high)
(let ((i (an-integer-between low high))
(hsq (* high high)))
(let ((j (an-integer-between i high)))
(let ((ksq (+ (* i i) (* j j))))
(require (>= hsq ksq))
(let ((k (sqrt ksq)))
(require (integer? k))
(list i j k))))))

18
mceval/amb-utilities.rkt Normal file
View File

@ -0,0 +1,18 @@
;; Lisp code to be evaluated by amb evaluator to implement utility procedures.
#lang sicp
(#%provide amb-utilities-program)
(define amb-utilities-program
'((define (require p)
(if (not p) (amb)))
(define (an-element-of items)
(require (not (null? items)))
(amb (car items) (an-element-of (cdr items))))
(define (an-integer-starting-from n)
(amb n (an-integer-starting-from (+ n 1))))))

View File

@ -2,7 +2,8 @@
#lang sicp
(#%require "syntax.rkt"
(#%require "amb-utilities.rkt"
"syntax.rkt"
"environment.rkt"
"common.rkt"
"special-forms.rkt")
@ -192,6 +193,18 @@
(define (driver-loop)
(define env (setup-environment))
;; Need to pass success and failure continuations to ambeval, so
;; will probably need a different eval-program.
(eval-program amb-utilities-program
(lambda (exp env) ; Evaluate exp using ambeval
; passing in appropriate
; continuations
(ambeval exp
env
(lambda (value fail) value)
(lambda () 'failed)))
user-print
env)
(define (internal-loop try-again)
(prompt-for-input input-prompt)
(let ((input (read)))