Skip to content

Instantly share code, notes, and snippets.

@davidallsopp
Last active August 29, 2015 14:16
Show Gist options
  • Save davidallsopp/214e2700d713d6bcdc7f to your computer and use it in GitHub Desktop.
Save davidallsopp/214e2700d713d6bcdc7f to your computer and use it in GitHub Desktop.
import Data.List (isPrefixOf)
numerals = [("M",1000),("CM",900),("D",500),("CD",400),("C",100),("XC",90),
("L",50),("XL",40),("X",10),("IX",9),("V",5),("IV",4),("I",1)]
toArabic :: String -> Int
toArabic "" = 0
toArabic str = num + toArabic xs
where (num, xs):_ = [ (num, drop (length n) str) | (n,num) <- numerals, isPrefixOf n str ]
-- Seems gratuitously unclear for the sake of a one-liner. How about:
toArabic2 :: String -> Int
toArabic2 "" = 0
toArabic2 str = n + toArabic xs
where xs = drop (length ch) str
Just (ch, n) = find ((`isPrefixOf` str) . fst ) numerals
@davidallsopp
Copy link
Author

The :_ = pattern match is the same as taking the head.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment