Last active
December 11, 2015 13:18
-
-
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/
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 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