Last active
June 15, 2017 10:22
-
-
Save purcell/5245e7233253b0621bbd5d678fae9afd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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