Created
September 20, 2010 21:05
-
-
Save petermarks/588647 to your computer and use it in GitHub Desktop.
Simple arithmetic expression language
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 Expressions where | |
import Data.Maybe | |
import Text.Printf | |
data Expr = Term Int | Op Operator Expr Expr | Var String | |
deriving (Show, Eq) | |
data Operator = Sum | Mult | Sub | Div | |
deriving (Show, Eq) | |
foldExpr :: (Int -> a) -> (Operator -> a -> a -> a) -> (String -> a) -> Expr -> a | |
foldExpr ft _ _ (Term i) = ft i | |
foldExpr ft fo fv (Op o u v) = fo o (foldExpr ft fo fv u) (foldExpr ft fo fv v) | |
foldExpr ft fo fv (Var id) = fv id | |
eval :: [(String, Int)] -> Expr -> Maybe Int | |
eval env = foldExpr Just applyOp getV | |
where | |
getV x = lookup x env | |
applyOp :: Operator -> Maybe Int -> Maybe Int -> Maybe Int | |
applyOp o (Just x) (Just y) = Just (getOp o x y) | |
applyOp _ _ _ = Nothing | |
getOp :: Operator -> Int -> Int -> Int | |
getOp o = case o of | |
Sum -> (+) | |
Mult -> (*) | |
Sub -> (-) | |
Div -> div | |
printExpr :: Expr -> String | |
printExpr = foldExpr show (flip (printf "(%s %s %s)") . printOp) id | |
printOp o = case o of | |
Sum -> "+" | |
Mult -> "*" | |
Sub -> "-" | |
Div -> "/" | |
countTerms :: Expr -> Int | |
countTerms = foldExpr (const 1) (const (+)) (const 1) | |
sample = Op Mult (Op Sum (Var "x") (Term 3)) (Term 4) |
Oops, that was slack. It seems we didn't actually compile that version in our haste at the end of the session. I've corrected it here now.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I had to change these lines:
26: printExpr = foldExpr show (\o u v -> printf "(%s %s %s)" u (printOp o) v)
35: countTerms = foldExpr (const 1) (_ -> (+))