]> git.rkrishnan.org Git - sicp.git/commitdiff
solution to 2.39. Took me some experimentation at the repl to find the fold-right...
authorRamakrishnan Muthukrishnan <vu3rdd@gmail.com>
Tue, 3 Aug 2010 19:36:05 +0000 (01:06 +0530)
committerRamakrishnan Muthukrishnan <vu3rdd@gmail.com>
Tue, 3 Aug 2010 19:36:05 +0000 (01:06 +0530)
src/sicp/ex2_39.clj [new file with mode: 0644]

diff --git a/src/sicp/ex2_39.clj b/src/sicp/ex2_39.clj
new file mode 100644 (file)
index 0000000..2a17b55
--- /dev/null
@@ -0,0 +1,33 @@
+(ns sicp.ex2_39
+  (:use [clojure.test]
+        [sicp [ch2-2 :only (accumulate)]
+              [ex2_36 :only (accumulate-n)]
+              [ex2_38 :only (fold-right fold-left)]]))
+
+;; Complete the following definitions of reverse (exercise 2.18) in
+;; terms of fold-right and fold-left from exercise 2.38:
+
+;; (define (reverse sequence)
+;;   (fold-right (lambda (x y) <??>) nil sequence))
+;; (define (reverse sequence)
+;;   (fold-left (lambda (x y) <??>) nil sequence))
+(defn reverse-with-foldr [sequence]
+  (fold-right (fn [x y]
+                (concat y (list x)))
+              nil
+              sequence))
+
+(defn reverse-with-foldl [sequence]
+  (fold-left (fn [x y]
+               (cons y x))
+             nil
+             sequence))
+
+(deftest test-reverses
+  (let [s1 '(1 2 3 4 5)
+        s2 '(1 2 3 (4 5))]
+    (are [x y] [= x y]
+         (reverse-with-foldr s1) (reverse s1)
+         (reverse-with-foldl s1) (reverse s1)
+         (reverse-with-foldr s2) (reverse s2)
+         (reverse-with-foldl s2) (reverse s2))))