RosettaCodeData/Task/Roman-numerals-Decode/Clojure/roman-numerals-decode.clj

16 lines
557 B
Clojure
Raw Permalink Normal View History

2016-12-05 22:15:40 +01:00
;; Incorporated some improvements from the alternative implementation below
2013-04-10 23:57:08 -07:00
(defn ro2ar [r]
2016-12-05 22:15:40 +01:00
(->> (reverse (.toUpperCase r))
(map {\M 1000 \D 500 \C 100 \L 50 \X 10 \V 5 \I 1})
2013-04-10 23:57:08 -07:00
(partition-by identity)
(map (partial apply +))
(reduce #(if (< %1 %2) (+ %1 %2) (- %1 %2)))))
2015-02-20 00:35:01 -05:00
;; alternative
(def numerals { \I 1, \V 5, \X 10, \L 50, \C 100, \D 500, \M 1000})
(defn from-roman [s]
(->> s .toUpperCase
(map numerals)
(reduce (fn [[sum lastv] curr] [(+ sum curr (if (< lastv curr) (* -2 lastv) 0)) curr]) [0,0])
first))