Created
March 12, 2017 09:20
-
-
Save devstopfix/20bfabc5fe4054d4adb01c8f2e77d290 to your computer and use it in GitHub Desktop.
Roman Numerals (Clojure)
This file contains hidden or 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
(ns roman-numerals.roman) | |
(def digits {\I 1 | |
\V 5 | |
\X 10 | |
\L 50 | |
\C 100 | |
\D 500 | |
\M 1000}) | |
(defn accumulate [acc [a,b]] | |
(if (>= a b) (+ acc a) (- acc a))) | |
(defn decode [s] | |
"Return the integer value of a string of Roman Numerals, | |
or nil if the string contains invalid characters." | |
(let [ds (map (partial get digits) (seq s))] | |
(when-not (some nil? ds) | |
(->> ds | |
(partition 2 1 [0]) | |
(reduce accumulate 0))))) | |
(decode "DCCCLXXXIV") | |
; 884 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment