Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@purcell
Last active June 15, 2017 10:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save purcell/5245e7233253b0621bbd5d678fae9afd to your computer and use it in GitHub Desktop.
Save purcell/5245e7233253b0621bbd5d678fae9afd to your computer and use it in GitHub Desktop.
module Main where
import Text.Parsec
import Text.Parsec.String
main :: IO ()
main = do
input <- getLine
case runP parseTree () "stdin" input of
Right n -> print (reduce n)
Left err -> print err
data Tree
= Cons Float
| Minus Tree Tree
| Plus Tree Tree
| Div Tree Tree
| Mult Tree Tree
deriving Show
reduce :: Tree -> Float
reduce (Cons x) = x
reduce (Plus x y) = (reduce x) + (reduce y)
reduce (Minus x y) = (reduce x) - (reduce y)
reduce (Mult x y) = (reduce x) * (reduce y)
reduce (Div x y) = (reduce x) / (reduce y)
parseTree :: Parser Tree
parseTree =
many space *> (
try (Cons <$> float) <|>
try (op "+" (Plus <$> parseTree <*> parseTree)) <|>
try (op "-" (Minus <$> parseTree <*> parseTree)) <|>
try (op "*" (Mult <$> parseTree <*> parseTree)) <|>
try (op "/" (Div <$> parseTree <*> parseTree))
)
where
float = read <$> many1 (digit <|> char '.') -- hacky af
op :: String -> Parser Tree -> Parser Tree
op o p = string o *> p
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment