public
Last active

Adding together two roman numerals to get a third one. See at: http://programmingpraxis.com/2009/03/06/roman-numerals/

  • Download Gist
pp_addRomans.hs
Haskell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.