Skip to content

Instantly share code, notes, and snippets.

@soofaloofa-zz
Created June 23, 2011 18:04
Show Gist options
  • Save soofaloofa-zz/1043147 to your computer and use it in GitHub Desktop.
Save soofaloofa-zz/1043147 to your computer and use it in GitHub Desktop.
4. Numbers Games
(defn add1 [n]
(+ n 1))
(defn sub1 [n]
(- n 1))
(defn plus [n m]
(cond
(zero? m) n
:else (add1 (plus n (sub1 m)))))
(defn minus [n m]
(cond
(zero? m) n
:else (sub1 (minus n (sub1 m))))
(defn addtup [tup]
(loop [t (seq tup) res 0]
(if t
(recur (next t) (+ (first t) res))
res)))
(defn tup+ [tup1 tup2]
(loop [t1 (seq tup1) t2 (seq tup2) res []]
(cond
(empty? t1) (concat res t2)
(empty? t2) (concat res t1)
:else (recur (next t1) (next t2) (conj res (+ (first t1) (first t2)))))))
(defn greater [n m]
(loop [x n y m]
(cond
(zero? x) false
(zero? y) true
:else (recur (sub1 x) (sub1 y)))))
(defn less [n m]
(loop [x n y m]
(cond
(zero? y) false
(zero? x) true
:else (recur (sub1 x) (sub1 y)))))
(defn equal [n m]
(cond
(greater n m) false
(less n m) false
:else true))
(defn power [n m]
(loop [x n y m res 1]
(if (zero? y)
res
(recur (sub1 x) (sub1 y) (* n res)))))
(defn divide [n m]
(loop [x n y m res 0]
(if (< x y)
res
(recur (- x y) y (add1 res)))))
(defn length [lat]
(loop [l (seq lat) res 0]
(if l
(recur (next l) (add1 res))
res)))
(defn pick [n lat]
(loop [l (seq lat) res 0]
(if l
(if (= n res)
(first l)
(recur (next l) (add1 res)))
res)))
(defn rempick [n lat]
(loop [l (seq lat) acc 0 res []]
(if l
(if (= n acc)
(concat res (next l))
(recur (next l) (add1 acc) (conj res (first l))))
res)))
(defn no-nums [lat]
(loop [l (seq lat) res []]
(if l
(if (number? (first l))
(recur (next l) res)
(recur (next l) (conj res (first l))))
res)))
(defn all-nums [lat]
(loop [l (seq lat) res []]
(if l
(if (number? (first l))
(recur (next l) (conj res (first l)))
(recur (next l) res))
(defn eqan? [a1 a2]
(cond
(and (number? a1) (number? a2)) (= a1 a2)
(or (number? a1) (number? a2)) false
:else (= a1 a2)))
(defn occur [a lat]
(loop [l (seq lat) res 0]
(if l
(if (= a (first l))
(recur (next l) (add1 res))
(recur (next l) res))
res)))
@soofaloofa-zz
Copy link
Author

Clojure functions for Chapter 4 of The Little Schemer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment