Last active
July 20, 2017 18:37
-
-
Save scvalencia/79b9f1a9b0f59670f890631e99ed89c4 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
data Expr = Const Int | |
| Var String | |
| Plus Expr Expr | |
| Minus Expr Expr | |
| Mul Expr Expr | |
type EnvType = [(String, Int)] | |
fetch_error :: String -> String | |
fetch_error str = "No variable of name " ++ str ++ " found!" | |
fetch_value :: EnvType -> String -> Maybe Int | |
fetch_value [] var = Nothing | |
fetch_value ((name, value):xs) var = | |
if name == var then Just value | |
else fetch_value xs var | |
eval :: EnvType -> Expr -> Int | |
eval env (Const x) = x | |
eval env (Var str) = case fetch_value env str of | |
Just x -> x | |
Nothing -> error . fetch_error $ str | |
eval env (Plus left right) = (eval env left) + (eval env right) | |
eval env (Minus left right) = (eval env left) - (eval env right) | |
eval env (Mul left right) = (eval env left) * (eval env right) | |
env :: EnvType | |
env = [("x", 2), ("y", 3)] | |
expression :: Expr | |
expression = (Mul | |
(Mul | |
(Plus (Var "x") (Var "y")) | |
(Minus (Const 24) (Const 12))) | |
(Minus (Const 79) (Var "y"))) | |
evaluation :: Int | |
evaluation = eval env expression | |
instance Show Expr where | |
show (Const x) = show x | |
show (Var str) = str | |
show (Plus left right) = "(" ++ (show left) ++ " + " ++ (show right) ++ ")" | |
show (Minus left right) = "(" ++ (show left) ++ " - " ++ (show right) ++ ")" | |
show (Mul left right) = "(" ++ (show left) ++ " * " ++ (show right) ++ ")" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment