Created
June 22, 2010 18:15
-
-
Save ragnard/448844 to your computer and use it in GitHub Desktop.
This file contains 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
;; | |
;; 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