Friday, January 8, 2010

To roman implementation in Clojure

Here is my take of to roman implementation in Clojure:
I posted this in http://rosettacode.org/wiki/Roman_Numerals#Clojure

1:  (def arabic-roman-map
2: {1 "I", 5 "V",
3: 10 "X", 50 "L",
4: 100 "C", 500 "D",
5: 1000 "M",
6: 4 "IV", 9 "IX",
7: 40 "XL", 90 "XC",
8: 400 "CD", 900 "CM" })
9: (def arabic-roman-map-sorted-keys
10: (sort (keys arabic-roman-map)))
11: (defn find-value-in-coll
12: [coll k]
13: (let [aval (find coll k)]
14: (if (nil? aval) "" (val aval))))
15: (defn to-roman
16: [result n]
17: (let
18: [closest-key-for-n (last (filter #(> n %) arabic-roman-map-sorted-keys))
19: roman-value-for-n (find-value-in-coll arabic-roman-map n)
20: roman-value-for-closet-to-n (find-value-in-coll arabic-roman-map
21: closest-key-for-n)]
22: (if (or (<= n 0) (contains? arabic-roman-map n))
23: (conj result roman-value-for-n)
24: (recur (conj result roman-value-for-closet-to-n)
25: (- n closest-key-for-n)))))
26: Usage: >(to-roman [] 1999)
27: result: ["M" "CM" "XC" "IX"]

No comments:

Post a Comment