Created
February 24, 2014 11:53
-
-
Save rylev/9187017 to your computer and use it in GitHub Desktop.
Simple and Incredibly Naive Calculator
This file contains hidden or 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 System.Environment | |
import Text.ParserCombinators.Parsec | |
import Control.Monad | |
import Data.Char | |
main :: IO () | |
main = do putStrLn "What would you like to calculate:" | |
input <- getLine | |
putStrLn $ readExpr input | |
readExpr :: String -> String | |
readExpr input = case parse parseExpr "calc" input of | |
Left err -> "Whoops, looks like you made a syntax error: " ++ show err | |
Right answer -> show $ reduceExpr answer | |
reduceExpr :: Expr -> Integer | |
reduceExpr expression = case expression of | |
Addition left right -> (reduceExpr left) + (reduceExpr right) | |
Subtraction left right -> (reduceExpr left) - (reduceExpr right) | |
Multiplication left right -> (reduceExpr left) * (reduceExpr right) | |
Division left right -> (reduceExpr left) `div` (reduceExpr right) | |
Value v -> v | |
data Expr = Value Integer | |
| Addition Expr Expr | |
| Subtraction Expr Expr | |
| Multiplication Expr Expr | |
| Division Expr Expr | |
deriving (Show) | |
parseExpr :: Parser Expr | |
parseExpr = (try parseAddition) | |
<|> (try parseSubtraction) | |
<|> (try parseMultiplication) | |
<|> (try parseDivision) | |
<|> parseValue | |
parseBinaryExpr :: Char -> (Expr -> Expr -> Expr) -> Parser Expr | |
parseBinaryExpr operator constructor = do spaces | |
left <- many1 digit | |
spaces | |
char operator | |
spaces | |
right <- many1 digit | |
return $ constructor ((Value . read) left) ((Value . read) right) | |
parseAddition :: Parser Expr | |
parseAddition = parseBinaryExpr '+' Addition | |
parseSubtraction :: Parser Expr | |
parseSubtraction = parseBinaryExpr '-' Subtraction | |
parseMultiplication :: Parser Expr | |
parseMultiplication = parseBinaryExpr '*' Multiplication | |
parseDivision :: Parser Expr | |
parseDivision = parseBinaryExpr '/' Division | |
parseValue :: Parser Expr | |
parseValue = do val <- many1 digit | |
return $ Value . read $ val |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Pretty cool. Still, it can be further simplified:
x
andy
instead ofleft
andright
is more idiomatic HaskellIsString
instance forParser
allows for further simplifications (this should actually be provided byparsec
...)