Commits

Anonymous committed 9619475

Haskell parser for Roman numerals

Comments (0)

Files changed (1)

haskell/Roman/Main.hs

+module Main where
+
+--import Control.Monad.State
+--import Data.Maybe
+import Data.Either
+import Control.Applicative((<$>))
+import System (getArgs)
+import Text.Parsec
+
+main :: IO ()
+main = do args <- getArgs
+          case (parseRoman $ args !! 0) of
+            Left err -> putStrLn $ show err
+            Right x  -> print x
+
+parseRoman :: String -> Either ParseError Int
+parseRoman input = parse roman "Error parsing numeral" input
+
+roman :: Parsec String () Int
+roman = do groups <- many parseGroup
+           return . sum $ map valGroup groups
+
+
+parseGroup = try (string "CM")
+             <|> try (string "CD")
+             <|> try (string "XC")
+             <|> try (string "XL")
+             <|> try (string "IX")
+             <|> try (string "IV")
+             <|> string "M"
+             <|> string "D"
+             <|> string "C"
+             <|> string "L"
+             <|> string "X"
+             <|> string "V"
+             <|> string "I"
+
+value :: Char -> Int
+value 'I' = 1
+value 'V' = 5
+value 'X' = 10
+value 'L' = 50
+value 'C' = 100
+value 'D' = 500
+value 'M' = 1000
+
+valGroup :: String -> Int
+valGroup [f,s] = (value s) - (value f)
+valGroup [x] = value x
+valGroup _  = error "impossible"