public
Last active

Simple arithmetic expression language

  • Download Gist
expressions.hs
Haskell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
module Expressions where
 
import Data.Maybe
import Text.Printf
import Control.Applicative
 
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 x y = getOp o <$> x <*> y
 
-- Or if you want to show off: applyOp = liftA2 . getOp
 
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)

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) (_ -> (+))

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.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.