Last active
June 4, 2023 21:07
-
-
Save Lev135/d6c0e56edc1a735c977f1485704e4953 to your computer and use it in GitHub Desktop.
Call by name?
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 Main where | |
import Data.Maybe (fromJust) | |
data Expr | |
= Var String | |
| Lam String Expr | |
| App Expr Expr | |
| Lit Int | |
| Prim PrimOp Expr Expr | |
| Let (String, Expr) Expr | |
deriving (Show) | |
data Value | |
= VInt Int | |
| VClosure String Expr Env | |
deriving (Show) | |
data PrimOp = Add | Mul deriving (Show) | |
type Env = [(String, Expr)] | |
eval :: Env -> Expr -> Value | |
eval env term = case term of | |
Var n -> eval env $ fromJust $ lookup n env | |
Lam n a -> VClosure n a env | |
App a b -> | |
let VClosure n c env' = eval env a in | |
eval ((n, b) : env') c | |
Lit n -> VInt n | |
Prim p a b -> (evalPrim p) (eval env a) (eval env b) | |
Let (n, e) e' -> eval ((n, e) : env) e' | |
evalPrim :: PrimOp -> Value -> Value -> Value | |
evalPrim Add (VInt a) (VInt b) = VInt (a + b) | |
evalPrim Mul (VInt a) (VInt b) = VInt (a + b) | |
emptyEnv :: Env | |
emptyEnv = [] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment