From: Ramakrishnan Muthukrishnan Date: Tue, 3 Aug 2010 18:16:01 +0000 (+0530) Subject: solution to 2.38 X-Git-Url: https://git.rkrishnan.org/vdrive/%22file:/frontends/status?a=commitdiff_plain;h=fc86bfbd60e451685bb34d329b4a5fdc99fb8ecf;p=sicp.git solution to 2.38 --- diff --git a/src/sicp/ex2_38.clj b/src/sicp/ex2_38.clj new file mode 100644 index 0000000..91f6818 --- /dev/null +++ b/src/sicp/ex2_38.clj @@ -0,0 +1,33 @@ +(ns sicp.ex2_38 + (:use [clojure.test] + [sicp [ch2-2 :only (accumulate)] + [ex2_36 :only (accumulate-n)]])) + +;; The accumulate procedure is also known as fold-right, because it combines +;; the first element of the sequence with the result of combining all the elements +;; to the right. There is also a fold-left, which is similar to fold-right, except +;; that it combines elements working in the opposite direction: +(def fold-right accumulate) + +(defn fold-left [op initial sequence] + (if (nil? sequence) + initial + (fold-left op + (op initial (first sequence)) + (next sequence)))) + +;; What are the values of +(comment + "answers inlined") + +(fold-right / 1 (list 1 2 3)) +;;=> 3/2 + +(fold-left / 1 (list 1 2 3)) +;;=> 1/6 + +(fold-right list nil (list 1 2 3)) +;;=> (1 (2 (3 nil))) + +(fold-left list nil (list 1 2 3)) +;;=> (((nil 1) 2) 3) \ No newline at end of file