Skip to content

Instantly share code, notes, and snippets.

@bananu7
Created January 12, 2014 20:56
Show Gist options
  • Save bananu7/8390520 to your computer and use it in GitHub Desktop.
Save bananu7/8390520 to your computer and use it in GitHub Desktop.
A parser of simple typed sums
import Text.ParserCombinators.Parsec
import Text.Parsec.Numbers
data Value = Kilometer Double | Mile Double
value = try valKm <|> valMile
valKm, valMile :: GenParser Char st Value
valKm = do
spaces
num <- parseFloat
char 'k'
char 'm'
return $ Kilometer num
valMile = do
spaces
num <- parseFloat
char 'm'
char 'l'
return $ Mile num
expression = do
result <- value `sepBy` (char '+')
eof
return result
toKm (Kilometer a) = a
toKm (Mile a) = a * 1.619
eval expr = foldl evaler 0 expr
where evaler accum value = accum + (toKm value)
parseE input = parse expression "(unknown)" input
main = do
l <- getLine
let e = parseE l
case e of
Right exp -> print $ eval exp
_ -> print "Parse Error"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment