Date to numeral system conversion with Clojure

That’s really funny. While I was writing an email, I run into a problem how to convert a date – written according to Polish regulations as dd.mm.yyyy – as a number in a numeral system with the minimum base to accommodate the symbols. Say, I want to convert 22.02.2011 into a number in base 3.

I knew I could do it in Clojure, but the final outcome wasn’t earth-shattering. Any tips and tricks how to improve it a bit to have it look more functional and Clojure idiomatic?

user=> (def n "22.02.2011")
#'user/n
user=> (defn digit? 1 (Character/isDigit c))
#'user/digit?
user=> (filter digit? n)
(\2 \2 \0 \2 \2 \0 \1 \1)
user=> (map #(Integer/parseInt (str %)) (filter digit? n))
(2 2 0 2 2 0 1 1)
user=> (def nns (map #(Integer/parseInt (str %)) (filter digit? n)))
#'user/nns
user=> (count nns)
8
user=> (range (count nns))
(0 1 2 3 4 5 6 7)
user=> (reverse nns)
(1 1 0 2 2 0 2 2)
user=> (reduce + (map #(* (Math/pow 3 %1) %2) (range (count nns)) (reverse nns)))
6052.0
Be Sociable, Share!
This entry was posted in Languages.

4 Responses to Date to numeral system conversion with Clojure

  1. Konrad Garus says:

    In the last line, you could use Horner’s rule (http://www.gettingclojure.com/cookbook:sequences):

    (reduce (fn [a b] (+ (* a x) b)) coefficients)

  2. Konrad Garus says:

    How about this one-liner:

    (reduce (fn [a b] (+ (* a 3) b)) (map #(Integer/parseInt %) (re-seq #”\d” “22.02.2011”)))

  3. anonymous says:

    (Integer/valueOf (.replace “22.02.2011” “.” “”) 3)

  4. Jacek Laskowski says:

    Thanks a lot for the answers. I learnt a lot – re-seq of Konrad and the one-liner of anonymous. Great!

Leave a Reply

%d bloggers like this: