module Problem89 where

import Data.List
import Data.Maybe

main :: IO ()
main = readFile "txt/89.txt" >>= print . sum . map characterSaved . lines

characterSaved :: String -> Int
characterSaved x = length x - length (write . value $ x)
  where
    value [] = 0
    value xs =
        (\(pre, val) -> val + value (fromJust $ stripPrefix pre xs))
            . head
            . filter (flip isPrefixOf xs . fst)
            $ romanSymbolValues
    write 0 = ""
    write n =
        (\(pre, val) -> pre ++ write (n - val))
            . head
            . filter ((<= n) . snd)
            $ romanSymbolValues
    romanSymbolValues =
        [ ("M" , 1000)
        , ("CM", 900)
        , ("D" , 500)
        , ("CD", 400)
        , ("C" , 100)
        , ("XC", 90)
        , ("L" , 50)
        , ("XL", 40)
        , ("X" , 10)
        , ("IX", 9)
        , ("V" , 5)
        , ("IV", 4)
        , ("I" , 1)
        ]
