Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save flengyel/1446313 to your computer and use it in GitHub Desktop.
Save flengyel/1446313 to your computer and use it in GitHub Desktop.
Read Roman Numerals (4clojure problem 92)
;; flengyel's solution to Read Roman numerals
;; https://4clojure.com/problem/92
;; 4clojure rates this as "hard" but I found it easy.
;; Uses a reduce with destructuring to keep track of the "accumulated state".
(fn [numeral]
(-> (let [roman {\I 1, \V 5, \X 10, \L 50, \C 100, \D 500, \M 1000}
digit (roman (first (vec numeral)))]
(reduce
(fn [[acc prv] cur]
(let [nacc (+ acc cur)]
[(if (< prv cur) (- nacc (* 2 prv)) nacc) cur]))
[digit digit] (map roman (rest (vec numeral))))) (first)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment