From: Ramakrishnan Muthukrishnan Date: Sun, 20 Nov 2011 05:16:49 +0000 (+0530) Subject: solutions to 4.12 and 4.13. X-Git-Url: https://git.rkrishnan.org/?a=commitdiff_plain;h=f7c95404a008e7ed6efdb2525cdf5d8a14a2f1ee;p=sicp.git solutions to 4.12 and 4.13. --- diff --git a/src/sicp/ex4_12.rkt b/src/sicp/ex4_12.rkt new file mode 100644 index 0000000..d918daf --- /dev/null +++ b/src/sicp/ex4_12.rkt @@ -0,0 +1,40 @@ +#lang racket + +;; given a frame, get the value of a given variable +;; false if not var is not found in the frame +(define (get-var-in-frame var frame) + ...) + +;; set a value for a given variable in a frame +;; if frame already contain var, change its binding, else +;; if frame does not have a binding for var, then create one. +(define (set-var-in-frame! var val frame) + ...) + +;; now using these two procedures, expressing `lookup-variable-value' +(define (lookup-variable-value var env) + (define (env-loop env) + (let ((frame (first-frame env))) + (let ((var-val (get-var-in-frame var frame))) + (if var-val + var-val + (env-loop (enclosing-environment env)))))) + (if (eq? env the-empty-environment) + (error "Unbound variable" var) + (env-loop env))) + + +(define (set-variable-value! var val env) + (define (env-loop env) + (let ((frame (first-frame env))) + (let ((var-val (get-var-in-frame var frame))) + (if var-val + (set-var-in-frame! var val frame) + (env-loop (enclosing-environment env)))))) + (if (eq? env the-empty-environment) + (error "Unbound variable -- SET!" var) + (env-loop env))) + +(define (define-variable! var val env) + (let ((frame (first-frame env))) + (set-var-in-frame! var val frame))) diff --git a/src/sicp/ex4_13.rkt b/src/sicp/ex4_13.rkt new file mode 100644 index 0000000..55535b2 --- /dev/null +++ b/src/sicp/ex4_13.rkt @@ -0,0 +1,21 @@ +#lang racket + +(define (make-unbound! var val env) + (let ((frame (first-frame env))) + (define (scan vars vals) + (cond ((null? vars) + (error "variable not bound" var)) + ((eq? var (car vars)) + (begin + (set-car! vals (cdr vals)) + (set-cdr! vars (cdr vars)))) + (else (scan (cdr vars) (cdr vals))))) + (scan (frame-variables frame) + (frame-values frame)))) + +#| + +Remove binding from the first frame, as removing it from elsewhere +would mean also removing all bindings built from it. + +|# \ No newline at end of file