Haskell Code
import qualified Data.Set as Set
-- ============================================================================
-- Syntax: Types and Terms
-- ============================================================================
data Type
= TBool
| TArrow Type Type
| TVar String
| TExists String Type
deriving (Show, Eq)
data Term
= Var String
| LitBool Bool
| Lam String Type Term
| App Term Term
| Pack Type Term Type -- pack {T1, e} as exists X. T2
| Unpack String String Term Term -- unpack (X, x) = e1 in e2
deriving (Show, Eq)
-- ============================================================================
-- Helper Functions (Free Type Variables & Type Substitution)
-- ============================================================================
ftv :: Type -> Set.Set String
ftv TBool = Set.empty
ftv (TVar x) = Set.singleton x
ftv (TArrow t1 t2) = Set.union (ftv t1) (ftv t2)
ftv (TExists x t) = Set.delete x (ftv t)
substType :: String -> Type -> Type -> Type
substType x t' TBool = TBool
substType x t' (TVar y)
| x == y = t'
| otherwise = TVar y
substType x t' (TArrow t1 t2) = TArrow (substType x t' t1) (substType x t' t2)
substType x t' (TExists y t)
| x == y = TExists y t
| otherwise = TExists y (substType x t' t)
-- ============================================================================
-- Type Checker
-- ============================================================================
type CtxT = [(String, Type)]
type Delta = Set.Set String
-- Check if a type is well-formed under type variable context Delta
checkType :: Delta -> Type -> Maybe ()
checkType delta TBool = Just ()
checkType delta (TVar x)
| x `Set.member` delta = Just ()
| otherwise = Nothing
checkType delta (TArrow t1 t2) = do
checkType delta t1
checkType delta t2
checkType delta (TExists x t) = do
checkType (Set.insert x delta) t
-- Type check a term under Delta (type vars) and Gamma (term vars)
typeCheck :: Delta -> CtxT -> Term -> Maybe Type
typeCheck delta gamma (Var x) = lookup x gamma
typeCheck delta gamma (LitBool _) = Just TBool
typeCheck delta gamma (Lam x ty e) = do
-- checkType delta ty
tyBody <- typeCheck delta ((x, ty) : gamma) e
Just (TArrow ty tyBody)
typeCheck delta gamma (App e1 e2) = do
t1 <- typeCheck delta gamma e1
t2 <- typeCheck delta gamma e2
case t1 of
TArrow tArg tRet | tArg == t2 -> Just tRet
_ -> Nothing
typeCheck delta gamma (Pack t1 e (TExists x t2)) = do
checkType delta t1
let expected = substType x t1 t2
actual <- typeCheck delta gamma e
if actual == expected
then Just (TExists x t2)
else Nothing
typeCheck delta gamma (Pack _ _ _) = Nothing
typeCheck delta gamma (Unpack x y e1 e2) = do
t1 <- typeCheck delta gamma e1
case t1 of
TExists z tInner -> do
let delta' = Set.insert x delta
let gamma' = (y, tInner) : gamma
t2 <- typeCheck delta' gamma' e2
if x `Set.member` ftv t2
then Nothing -- Scope escape check: abstract type variable cannot leak into return type
else Just t2
_ -> Nothing