From: Ramakrishnan Muthukrishnan Date: Sun, 27 May 2012 16:31:03 +0000 (+0530) Subject: Solutions to 4.27, 4.28 and 4.29. X-Git-Url: https://git.rkrishnan.org/%5B/frontends/flags/%22file:/(%5B%5E?a=commitdiff_plain;h=c6a6e187ad34b393587f51d181e2751f82f41aff;p=sicp.git Solutions to 4.27, 4.28 and 4.29. --- diff --git a/src/sicp/ex4_27.rkt b/src/sicp/ex4_27.rkt new file mode 100644 index 0000000..6013958 --- /dev/null +++ b/src/sicp/ex4_27.rkt @@ -0,0 +1,38 @@ +#lang racket + +(require "metacircular2-lazy.rkt") + +(define env1 (make-environment)) +(eval '(define count 0) env1) +(eval '(define (id x) (set! count (+ count 1)) x) env1) + +#| + +> (eval '(define w (id (id 0))) env1) +> (eval 'count env1) +1 +> (eval 'w env1) +#0='(thunk + (id 0) + #1=(#hash((< . (primitive #)) + (* . (primitive #)) + (> . (primitive #>)) + (- . (primitive #)) + (= . (primitive #)) + (true . #t) + (+ . (primitive #)) + (list . (primitive #)) + (null? . (primitive #)) + (/ . (primitive #)) + (car . (primitive #)) + (false . #f) + (cdr . (primitive #)) + (cons . (primitive #)) + (count . 1) + (id . (procedure (x) ((set! count (+ count 1)) x) #1#)) + (w . #0#)))) +> (eval 'count env1) +1 +> + +|# \ No newline at end of file diff --git a/src/sicp/ex4_28.rkt b/src/sicp/ex4_28.rkt new file mode 100644 index 0000000..c241853 --- /dev/null +++ b/src/sicp/ex4_28.rkt @@ -0,0 +1,18 @@ +#lang racket + +(require "metacircular2-lazy.rkt") + +#| +Forcing is needed for any higher order procedure. An example is map. If you evaluate the following +code with `actual-value' instead of `eval' of operator, it executes fine but if not, then eval gets +a thunk object (the two operands) for evaluation and when it reaches `apply' inside the `cons' it +will fail as `apply' does not know about thunk objects. +|# + +(define env1 (make-environment)) +(eval '(define (map f xs) + (if (null? xs) + '() + (cons (f (car xs)) (map f (cdr xs))))) + env1) +(eval '(map (lambda(x) (* x x)) '(1 2 3)) env1) \ No newline at end of file diff --git a/src/sicp/ex4_29.rkt b/src/sicp/ex4_29.rkt new file mode 100644 index 0000000..1c1a976 --- /dev/null +++ b/src/sicp/ex4_29.rkt @@ -0,0 +1,11 @@ +#lang racket + +#| + +Any program which will call itself or another function recursively or repeatedly (as another argument) +will benefit from memoization. + +non-memoized version will have count of 2 as x gets forced twice in the expression (* x x). In memoized +version, it will be 1. + +|# \ No newline at end of file