Created
October 22, 2016 19:22
-
-
Save ondrejsevcik/b7dc021de6f7397aafd77fc15a566b25 to your computer and use it in GitHub Desktop.
Roman numerals kata in Elm
This file contains 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
import Html exposing (..) | |
--Helper function from elm-list-extra | |
find : (a -> Bool) -> List a -> Maybe a | |
find predicate list = | |
case list of | |
[] -> | |
Nothing | |
first::rest -> | |
if predicate first then | |
Just first | |
else | |
find predicate rest | |
conversionTable = | |
[ (1000, "M") | |
, (900, "CM") | |
, (500, "D") | |
, (400, "CD") | |
, (100, "C") | |
, (90, "XC") | |
, (50, "L") | |
, (40, "XL") | |
, (10, "X") | |
, (9, "IX") | |
, (5, "V") | |
, (4, "IV") | |
, (1, "I") | |
] | |
toRomanNumber arabicInput = | |
if arabicInput <= 0 then | |
"" | |
else | |
let | |
(arabic, roman) = | |
Maybe.withDefault (0, "") | |
<| find (\(a, r) -> a <= arabicInput) conversionTable | |
in | |
roman ++ toRomanNumber(arabicInput - arabic) | |
test input expected = | |
div [] [text <| toRomanNumber(input) ++ " = " ++ expected] | |
main = | |
div [] | |
[ test 0 "" | |
, test 1 "I" | |
, test 99 "XCIX" | |
, test 1000 "M" | |
, test 3629 "MMMDCXXIX" | |
, test 10000 "MMMMMMMMMM" | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment