Skip to content

Instantly share code, notes, and snippets.

@ooharak
Created December 10, 2012 04:58
Show Gist options
  • Save ooharak/4248454 to your computer and use it in GitHub Desktop.
Save ooharak/4248454 to your computer and use it in GitHub Desktop.
Roman numeric converter in Haskell
module Roman
where
roman' n (one:five:ten:[]) | n == 0 = []
| n == 4 = [one, five]
| n == 5 = [five]
| n == 9 = [one, ten]
| n > 5 = five : (roman' (n-5) (one:five:ten:[]) )
| otherwise = (roman' (n-1) (one:five:ten:[]) ) ++ [one]
--roman::Integral a=>a->String
roman n | 1 <= n && n < 10 = roman' n $ part 0
| 10 <= n && n < 100 = roman' (div n 10) (part 2) ++ rest (mod n 10)
| 100 <= n && n < 1000 = roman' (div n 100) (part 4) ++ rest (mod n 100)
| 1000 <= n && n < 4000 = roman' (div n 1000) (part 6) ++ rest (mod n 1000)
where rest n | n == 0 = ""
| otherwise = roman n
part n = take 3 $ drop n "IVXLCDM--"
chkroman n | n < 1 = Nothing
| n < 4000 = Just $ roman n
| otherwise = Nothing
deroman s = head $ filter (\n -> s == roman n) [1..3999]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment