Created
May 3, 2011 20:03
-
-
Save pingles/954110 to your computer and use it in GitHub Desktop.
Working through some of the 4clojure.com examples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns four-clojure | |
(:use clojure.test)) | |
(defn pen [coll] | |
(last (drop-last coll))) | |
(deftest penultimate-element | |
(is (= (pen (list 1 2 3 4 5)) 4)) | |
(is (= (pen ["a" "b" "c"]) "b")) | |
(is (= (pen [[1 2] [3 4]]) [1 2]))) | |
(defn nth2 | |
[coll n] | |
(if (= n 0) | |
(first coll) | |
(recur (rest coll) (dec n)))) | |
(deftest nth-element | |
(is (= (nth2 '(4 5 6 7) 2) 6)) | |
(is (= (nth2 [:a :b :c] 0) :a)) | |
(is (= (nth2 [1 2 3 4] 1) 2)) | |
(is (= (nth2 '([1 2] [3 4] [5 6]) 2) [5 6]))) | |
(defn count2 | |
([coll] | |
(count2 coll 0)) | |
([coll ac] | |
(if (nil? (seq coll)) | |
ac | |
(recur (rest coll) (inc ac))))) | |
(deftest count-a-sequence | |
(is (= (count2 '(1 2 3 3 1)) 5)) | |
(is (= (count2 "Hello World") 11)) | |
(is (= (count2 [[1 2] [3 4] [5 6]]) 3)) | |
(is (= (count2 '(13)) 1)) | |
(is (= (count2 '(:a :b :c)) 3))) | |
(defn reverse2 | |
[coll & x] | |
(if (nil? (seq coll)) | |
x | |
(recur (rest coll) (cons (first coll) x)))) | |
(deftest reverse-a-sequence | |
(is (= (reverse2 [1 2 3 4 5]) [5 4 3 2 1])) | |
(is (= (reverse2 (sorted-set 5 7 2 7)) '(7 5 2))) | |
(is (= (reverse2 [[1 2][3 4][5 6]]) [[5 6][3 4][1 2]]))) | |
(defn sum | |
[coll] | |
(reduce + coll)) | |
(deftest sum-it-all-up | |
(is (= (sum [1 2 3]) 6)) | |
(is (= (sum (list 0 -2 5 5)) 8)) | |
(is (= (sum #{4 2 1}) 7)) | |
(is (= (sum '(0 0 -1)) -1)) | |
(is (= (sum '(1 10 3)) 14))) | |
(defn odd-numbers | |
[xs] | |
(filter odd? xs)) | |
(deftest find-the-odd-numbers | |
(is (= (odd-numbers #{1 2 3 4 5}) '(1 3 5))) | |
(is (= (odd-numbers [4 2 1 6]) '(1))) | |
(is (= (odd-numbers [2 2 4 6]) '())) | |
(is (= (odd-numbers [1 1 1 3]) '(1 1 1 3)))) | |
(defn fib-n | |
([n] | |
(fib-n (- n 2) [1 1])) | |
([n xs] | |
(if (= n 0) | |
xs | |
(recur (dec n) (conj xs (+ (last xs) | |
(last (drop-last xs)))))))) | |
(deftest fibonacci-sequence | |
(is (= (fib-n 3) '(1 1 2))) | |
(is (= (fib-n 6) '(1 1 2 3 5 8))) | |
(is (= (fib-n 8) '(1 1 2 3 5 8 13 21)))) | |
(defn palindrome? | |
[x] | |
(every? (fn [[a b]] (= a b)) | |
(partition 2 (interleave x (reverse x))))) | |
(deftest palindrome-detector | |
(is (false? (palindrome? '(1 2 3 4 5)))) | |
(is (true? (palindrome? "racecar"))) | |
(is (true? (palindrome? [:foo :bar :foo]))) | |
(is (true? (palindrome? '(1 1 3 3 1 1)))) | |
(is (false? (palindrome? '(:a :b :c))))) | |
(run-tests) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment