Skip to content

Instantly share code, notes, and snippets.

@ExcaliburZero
Created March 22, 2017 18:48
Show Gist options
  • Save ExcaliburZero/8f3e7dcb307cdc605e4b973af4a787cf to your computer and use it in GitHub Desktop.
Save ExcaliburZero/8f3e7dcb307cdc605e4b973af4a787cf to your computer and use it in GitHub Desktop.
Oswego CSA - Haskell Workshop Code
module Lib where
import Text.Parsec
import Text.Parsec.String (Parser)
someFunc :: IO ()
someFunc = putStrLn "someFunc"
numberStringParser :: Parser String
numberStringParser = many1 digit
numberParser :: Parser Int
numberParser = fmap read numberStringParser
data Operator = Add | Subtract
deriving (Show)
readOperator :: String -> Operator
readOperator "+" = Add
readOperator "-" = Subtract
readOperator _ = error "Undefined operator"
addParser :: Parser String
addParser = string "+"
subtractParser :: Parser String
subtractParser = string "-"
operatorStringParser :: Parser String
operatorStringParser = addParser <|> subtractParser
operatorParser :: Parser Operator
operatorParser = fmap readOperator operatorStringParser
data Expression = Literal Int | Operation Expression Operator Expression
deriving (Show)
literalParser :: Parser Expression
literalParser = fmap Literal numberParser
operationParser :: Parser Expression
operationParser = do
_ <- string "("
firstExp <- expressionParser
operator <- operatorParser
secondExp <- expressionParser
_ <- string ")"
let expression = Operation firstExp operator secondExp
return expression
expressionParser :: Parser Expression
expressionParser = operationParser <|> literalParser
performOperation :: Operator -> Int -> Int -> Int
performOperation Add a b = a + b
performOperation Subtract a b = a - b
evaluate :: Expression -> Int
evaluate (Literal n) = n
evaluate (Operation exp1 op exp2) = performOperation op (evaluate exp1) (evaluate exp2)
evaluationParser :: Parser Int
evaluationParser = fmap evaluate expressionParser
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment