DEV Community

Discussion on: Daily Challenge #209 - Roman Numerals

Collapse
 
cipharius profile image
Valts Liepiņš

My solution in Haskell:

solution :: String -> Int
solution = parser . fmap lexer
  where
    parser :: [Int] -> Int
    parser []     = 0
    parser (x:[]) = x
    parser (x:x':xs)
      | x >= x'   = x + (parser (x':xs))
      | otherwise = -x + x' + (parser xs)

    lexer :: Char -> Int
    lexer s =
      case s of
        'I' -> 1
        'V' -> 5
        'X' -> 10
        'L' -> 50
        'C' -> 100
        'D' -> 500
        'M' -> 1000

The lexer function takes care of translating roman numeral tokens into numbers, which can be applied to whole string to get array of the respective integers.
The array of integers is then parsed with a recursive function.

I went with case in lexer, since that notation seemed neater than defining function for each argument case.