From: Ramakrishnan Muthukrishnan Date: Sun, 17 Oct 2010 19:17:56 +0000 (+0530) Subject: solution to 2.34, 2.35, 2.36 and 2.37 X-Git-Url: https://git.rkrishnan.org/pf/content/en/service/(%5B%5E?a=commitdiff_plain;h=e2fa397aae723d9c5ea05890f1507c260641e04d;p=sicp.git solution to 2.34, 2.35, 2.36 and 2.37 --- diff --git a/src/sicp/ex2_34.rkt b/src/sicp/ex2_34.rkt new file mode 100644 index 0000000..aa671fe --- /dev/null +++ b/src/sicp/ex2_34.rkt @@ -0,0 +1,10 @@ +#lang racket + +(require "utils.rkt") + +(define (horner-eval x coefficient-sequence) + (accumulate (lambda (this-coeff higher-terms) (+ (* x this-coeff) higher-terms)) + 0 + coefficient-sequence)) + +(horner-eval 2 '(1 3 0 5 0 1)) \ No newline at end of file diff --git a/src/sicp/ex2_35.rkt b/src/sicp/ex2_35.rkt new file mode 100644 index 0000000..23e7e09 --- /dev/null +++ b/src/sicp/ex2_35.rkt @@ -0,0 +1,8 @@ +#lang racket + +(require "utils.rkt") + +(define (count-leaves t) + (accumulate + + 0 + (map (lambda (x) (if (pair? x) (count-leaves x) 1)) t))) \ No newline at end of file diff --git a/src/sicp/ex2_36.rkt b/src/sicp/ex2_36.rkt new file mode 100644 index 0000000..658b860 --- /dev/null +++ b/src/sicp/ex2_36.rkt @@ -0,0 +1,13 @@ +#lang racket + +(require "utils.rkt") + +(define (accumulate-n op init seqs) + (if (null? (car seqs)) + '() + (cons (accumulate op init (map car seqs)) + (accumulate-n op init (map cdr seqs))))) + +(provide accumulate-n) + +;; (accumulate-n + 0 '((1 2 3) (4 5 6) (7 8 9) (10 11 12))) \ No newline at end of file diff --git a/src/sicp/ex2_37.rkt b/src/sicp/ex2_37.rkt new file mode 100644 index 0000000..841e6c2 --- /dev/null +++ b/src/sicp/ex2_37.rkt @@ -0,0 +1,24 @@ +#lang racket + +(require "utils.rkt" + "ex2_36.rkt") + +;; dot product +(define (dot-product v w) + (accumulate + 0 (map * v w))) + +(define (matrix-*-vector m v) + (map (lambda (r) (dot-product r v)) m)) + +;; (matrix-*-vector '((1 2 3 4) (4 5 6 6) (6 7 8 9)) '(1 2 3 4)) + +(define (transpose m) + (accumulate-n cons '() m)) + +;; (transpose '((1 2 3) (4 5 6) (7 8 9))) + +(define (matrix-*-matrix m n) + (let ([cols (transpose n)]) + (map (lambda (v) (matrix-*-vector cols v)) m))) + +;; (matrix-*-matrix '((0 -1 2) (4 11 2)) '((3 -1) (1 2) (6 1))) \ No newline at end of file