Haskell Code
import qualified Data.Map as Map
type Var = String
data Type
= TBool
| TArr Type Type
deriving (Eq, Show)
data Expr
= Var Var
| Abs Var Type Expr
| App Expr Expr
| LBool Bool
| If Expr Expr Expr
| FixRec Var Var Type Type Expr
deriving (Eq, Show)
type Context = Map.Map Var Type
typecheck :: Context -> Expr -> Either String Type
typecheck ctx (Var x) =
case Map.lookup x ctx of
Just t -> Right t
Nothing -> Left $ "Unbound variable: " ++ x
typecheck ctx (Abs x tArg body) = do
tBody <- typecheck (Map.insert x tArg ctx) body
Right (TArr tArg tBody)
typecheck ctx (App e1 e2) = do
t1 <- typecheck ctx e1
t2 <- typecheck ctx e2
case t1 of
TArr tArg tRet
| tArg == t2 -> Right tRet
| otherwise -> Left $ "Type mismatch in application: expected " ++ show tArg ++ ", got " ++ show t2
_ -> Left "Attempted to apply a non-function term"
typecheck _ (LBool _) = Right TBool
typecheck ctx (If eCond eThen eElse) = do
tCond <- typecheck ctx eCond
if tCond /= TBool
then Left "Condition in If-expression must be Bool"
else do
tThen <- typecheck ctx eThen
tElse <- typecheck ctx eElse
if tThen == tElse
then Right tThen
else Left "Branch type mismatch in If-expression"
typecheck ctx (FixRec f x t1 t2 body) = do
let ctx' = Map.insert f (TArr t1 t2) (Map.insert x t1 ctx)
tBody <- typecheck ctx' body
if tBody == t2
then Right (TArr t1 t2)
else Left $ "FixRec body type mismatch: expected " ++ show t2 ++ ", got " ++ show tBody