From aaf28b08714d04a612112b08e2d0c7565422c878 Mon Sep 17 00:00:00 2001 From: Samppalol Date: Sat, 26 Oct 2013 02:20:11 +0300 Subject: [PATCH] done a few more --- .nrepl-port | 1 + src/recursion.clj | 43 ++++++++++++++++++++++++++++++++++++------- 2 files changed, 37 insertions(+), 7 deletions(-) create mode 100644 .nrepl-port diff --git a/.nrepl-port b/.nrepl-port new file mode 100644 index 0000000..0615d2c --- /dev/null +++ b/.nrepl-port @@ -0,0 +1 @@ +59918 \ No newline at end of file diff --git a/src/recursion.clj b/src/recursion.clj index 3e41417..2b0bf6f 100644 --- a/src/recursion.clj +++ b/src/recursion.clj @@ -1,14 +1,21 @@ + (ns recursion) (defn product [coll] (if (empty? coll) - 0 + 1 (* (first coll) (product (rest coll))))) ; The if acts as our base case, otherwise the function ; will recursively call itself. +;(product []) ;=> 1 ; special case +;(product [1 2 3]) ;=> 6 +;(product [1 2 3 4]) ;=> 24 +;(product [0 1 2]) ;=> 0 +;(product #{2 3 4}) ;=> 24 ; works for sets too! + (defn singleton? [coll] (if (not (nil? (first coll))) (nil? (first (rest coll))) false) ) @@ -102,13 +109,21 @@ (defn seq= [a-seq b-seq] (cond - (and (empty? a-seq) (empty? b-seq)) true + (and (empty? a-seq) (empty? a-seq)) (= (first a-seq) (first b-seq)) + (or (empty? a-seq) (empty? b-seq)) false + (and (empty? (rest a-seq)) (empty? (rest b-seq)) ) (= (first a-seq) (first b-seq)) (= (first a-seq) (first b-seq)) (seq= (rest a-seq) (rest b-seq)) :else false)) ;(seq= [1 2 4] '(1 2 4)) ;=> true ;(seq= [1 2 3] [1 2 3 4]) ;=> false ;(seq= [1 3 5] []) ;=> false +;(seq= [1 2 4] '(1 2 4)) ;=> true +;(seq= [] []) ;=> true +;(seq= [1 2 nil] [1 2]) ;=> false +;(seq= [1 4 2] [1 2 4]) ;=> false +;(seq= [1 2 3] [1 2 3 4]) ;=> false +;(seq= [1 3 5] []) ;=> false (defn my-map [f seq-1 seq-2] (cond @@ -174,7 +189,7 @@ (let [ b-seq (reverse a-seq)] (map reverse (tails b-seq)))) -(inits [1 2 3 4]) ;=> (() (1) (1 2) (1 2 3) (1 2 3 4)) +;(inits [1 2 3 4]) ;=> (() (1) (1 2) (1 2 3) (1 2 3 4)) (defn rotations [a-seq] ;(cond @@ -194,19 +209,31 @@ -(my-frequencies [:a "moi" :a "moi" "moi" :a 1]) ;=> {:a 3, "moi" 3, 1 1} +;(my-frequencies [:a "moi" :a "moi" "moi" :a 1]) ;=> {:a 3, "moi" 3, 1 1} (defn un-frequencies [a-map] [:-]) (defn my-take [n coll] - [:-]) + (if (or (empty? coll) (zero? n)) '() (cons (first coll) (my-take (dec n)(rest coll))) )) + +;(my-take 2 [1 2 3 4]) ;=> (1 2) +;(my-take 4 [:a :b]) ;=> (:a :b) (defn my-drop [n coll] - [:-]) + (if (or (empty? coll) (> 1 n)) coll (my-drop (dec n) (rest coll)) )) + +;(my-drop 2 [1 2 3 4]) ;=> (3 4) +;(my-drop 4 [:a :b]) ;=> () (defn halve [a-seq] - [:-]) + (vector (my-take (int (/ (count a-seq) 2)) a-seq) (my-drop (/ (count a-seq) 2) a-seq))) + +;(halve [1 2 3 4]) ;=> [(1 2) (3 4)] +;(halve [1 2 3 4 5]) ;=> [(1 2) (3 4 5)] +;(halve [1]) ;=> [() (1)] + +;(concat [1 2 3] [4]) (defn seq-merge [a-seq b-seq] [:-]) @@ -229,4 +256,6 @@ + +