From fc86bfbd60e451685bb34d329b4a5fdc99fb8ecf Mon Sep 17 00:00:00 2001 From: Ramakrishnan Muthukrishnan Date: Tue, 3 Aug 2010 23:46:01 +0530 Subject: [PATCH] solution to 2.38 --- src/sicp/ex2_38.clj | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 src/sicp/ex2_38.clj 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 -- 2.45.2