Skip to content

Instantly share code, notes, and snippets.

@ragnard
Created June 22, 2010 18:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ragnard/448844 to your computer and use it in GitHub Desktop.
Save ragnard/448844 to your computer and use it in GitHub Desktop.
;;
;; Implementation of exercise 2 found at:
;; http://www.knowing.net/index.php/2006/06/16/15-exercises-to-know-a-programming-language-part-1/
;;
;; Part of code sparring evening at the first SCLOJUG meeting,
;; unfinished then, finished now.
;;
;; Horrible specification btw.
;;
(defn abs
"Return the absolute value of n"
[n]
(if (neg? n)
(- n)
n))
(defn mean
"Calculate mean value of collection"
[coll]
(let [sum (reduce + coll)]
(/ sum (count coll))))
(defn- haar-pair
"Calculate average, and difference from the average for a and b"
[a b]
(let [avg (mean [a b])
diff (abs (- a avg))]
[avg diff]))
(defn- haar-step
"Apply the Haar transform once to a collection of pairs"
[pairs]
(apply interleave
(map
#(apply haar-pair %)
(partition 2 pairs))))
(defn haar
"Calculate the Haar wavelet of a collection of pairs"
[pairs]
{:pre [(even? (count pairs))]}
(let [avg (mean pairs)]
(loop [res pairs]
(if (= (first res) avg)
res
(recur (haar-step res))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment