Tuesday, December 7, 2010

Playing with Clojure

I have been playing with Clojure more and more lately, looking for simple problems to improve my understanding of it. One thing I was able to find while surfing on the Internet was the problem about the 'longest common subsequence' of numbers in a collection. I remember writing code for it some time ago in Java - this being code with counters for "max_repeating_so_far" and "max_repeating_in_sequence" numbers, etc., plus some dynamic programming added on top of it. I'm regularly being amazed by the compactness of the code for problems alike when using Clojure (my code here is surely not optimal, but it's been fun):

user=> (def nums '(2 1 1 2 3 3 2 2 2 1))
#'user/nums
user=> (def sublists (partition-by identity nums))
#'user/sublists
user=> sublists
((2) (1 1) (2) (3 3) (2 2 2) (1))
user=> (reduce max (map count sublists))
3
user=> (doseq [numlist sublists]
(when (= (count numlist) (reduce max (map count sublists)))
(println numlist)))
(2 2 2)
nil


Having too much free time, that's a program of mine for calculating sine using Taylor's formula:
(defn fact [n]
(reduce * (take n (iterate inc 1))))

(defn sin-iteration [x n]
(/ (* (Math/pow -1 n)
(Math/pow x (+ (* 2 n) 1)))
(fact (+ (* 2 n) 1))))

(defn sin [x n]
(let [res (atom 0)]
(dotimes [iteration-counter n]
(swap! res #(+ (sin-iteration x iteration-counter) %)))
@res))

;;user=> (sin 0.52359 10)
;;0.4999924000896871

Categories

code (15) fun (2) linux (31) miscellaneous (9) music (8)

About me

I'm Adrian and this is my blog. Here I usually write about technical stuff (mostly about Linux).
Copyright: BY-NC_SA, Author: aeter