Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@AndrasKovacs
Last active December 11, 2015 13:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndrasKovacs/4606068 to your computer and use it in GitHub Desktop.
Save AndrasKovacs/4606068 to your computer and use it in GitHub Desktop.
Adding together two roman numerals to get a third one. See at: http://programmingpraxis.com/2009/03/06/roman-numerals/
import Data.Map (fromList, (!))
romans = zip (words "M CM D CD C XC L XL X IX V IV I") [1000,900,500,400,100,90,50,40,10,9,5,4,1]
romMap = fromList romans
toRoman = go romans where
go _ 0 = ""
go a@((r, c):rs) n | c <= n = r ++ go a (n - c)
| otherwise = go rs n
toArab n = c + sum [b - 2 * a * fromEnum (b > a) | (a, b) <- zip conv cs] where
conv@(c:cs) = map ((romMap!) . (:[])) n
addRomans a b = toRoman (toArab a + toArab b)
main = print $ addRomans "IV" "XXIV"
--Slower but terser conversions with no Data.Map (about half as fast)
--toRoman 0 = ""
--toRoman n = r ++ toRoman (n - c) where
-- (r, c) = head $ filter ((<=n) . snd) romans
--toArab n = c + sum [b - 2 * a * fromEnum (b > a) | (a, b) <- zip conv cs] where
-- conv@(c:cs) = map (fromJust . (`lookup` romans) . (:[])) n
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment