From: Ramakrishnan Muthukrishnan Date: Sat, 7 Aug 2010 09:21:23 +0000 (+0530) Subject: examples upto ex 2.40 X-Git-Url: https://git.rkrishnan.org/components/com_hotproperty/css/module-simplejson.html?a=commitdiff_plain;h=8e8342673bb35fe28b89b43eda40b694abf3833f;p=sicp.git examples upto ex 2.40 --- diff --git a/src/sicp/ch2_2.clj b/src/sicp/ch2_2.clj index 30fd55b..93fdcfb 100644 --- a/src/sicp/ch2_2.clj +++ b/src/sicp/ch2_2.clj @@ -1,6 +1,6 @@ (ns sicp.ch2-2 - (:refer-clojure :exclude (map)) - (:use [sicp [ch1-2 :only (fib)]] + (:refer-clojure :exclude (map remove)) + (:use [sicp [ch1-2 :only (fib prime?)]] [clojure.test])) (cons 1 @@ -206,3 +206,44 @@ (map square ,,,) (accumulate * 1 ,,,))) +;; nested mapping +(accumulate append + nil + (map (fn [i] + (map (fn [j] (list i j)) + (enumerate-interval 1 (- i 1)))) + (enumerate-interval 1 6))) + +(defn flatmap [proc xs] + (accumulate append nil (map proc xs))) + +(defn prime-sum? [pair] + (prime? (+ (first pair) + (first (rest pair))))) + +;;; create the triple (i,j,sum) +(defn make-pair-sum [pair] + (list (first pair) + (first (rest pair)) + (+ (first pair) + (first (rest pair))))) + +(defn prime-sum-pairs [n] + (map make-pair-sum + (filter prime-sum? + (flatmap (fn [i] + (map (fn [j] (list i j)) + (enumerate-interval 1 (- i 1)))) + (enumerate-interval 1 n))))) + +;;; permutations +(defn remove [item sequence] + (filter (fn [x] (not= item x)) sequence)) + +(defn permutations [s] + (if (empty? s) + (list nil) + (flatmap (fn [x] + (map (fn [p] (cons x p)) + (permutations (remove x s)))) + s))) \ No newline at end of file