Share Pastebin
Guest
Public paste!

Tiago Cogumbreiro

By: a guest | Feb 3rd, 2009 | Syntax: Haskell | Size: 1.97 KB | Hits: 54 | Expires: Never
Copy text to clipboard
  1. data Type = UnitType | TypeVar String | ArrowType Type Type
  2.  
  3. -- Pretty print types
  4.  
  5. instance Show Type where show UnitType = "Unit" show (TypeVar x) = x
  6.     show (ArrowType t1 t2) = "(" ++ (show t1) ++ " -> " ++ (show t2)
  7.     ++ ")"
  8.  
  9. -- Expressions
  10.  
  11. data Expr = Unit | Var String | App Expr Expr | Fun String Expr
  12.  
  13. type TypeAssign = (String, Type)
  14.  
  15. type TypeEnv = [TypeAssign]
  16.  
  17. -- pretty print values
  18.  
  19. instance Show Expr where show Unit = "unit" show (Var x) = x show (App
  20.     e1 e2) = "(" ++ (show e1) ++ " " ++ (show e2) ++ ")" show (Fun x
  21.     e) = "(fun " ++ x ++ " = " ++ (show e) ++ ")"
  22.  
  23. env_lookup:: TypeEnv -> String -> Type
  24.  
  25. env_lookup ((x,t):xs) y | x == y = t | otherwise = (env_lookup xs y)
  26.  
  27. env_lookup [] x = error ("Key `" ++ x ++ "' not found.")
  28.  
  29. -- Functions to generate fresh type-variables:
  30.  
  31. numsFrom n = n : numsFrom (n + 1)
  32.  
  33. naturals = numsFrom 1
  34.  
  35. listOf x = x : listOf x
  36.  
  37. strNaturals = map show naturals
  38.  
  39. genNames name = map (uncurry (++)) (zip (listOf name) strNaturals)
  40.  
  41. genTypeVars name = map (\ x -> TypeVar x) (genNames name)
  42.  
  43. -- The result type
  44.  
  45. data Constraint = Eq Type Type
  46.  
  47. -- Make it print'able instance Show Constraint where show (Eq t1 t2) =
  48. (show t1) ++ "=" ++ (show t2)
  49.  
  50. -- The algorithm to infer types
  51.  
  52. infer:: TypeEnv -> Expr -> Type -> [Type] -> [Constraint]
  53.  
  54. infer _ Unit t vars = [Eq t UnitType]
  55.  
  56. infer type_env (Var x) t vars = [(Eq ret_type t)] where ret_type =
  57.     env_lookup type_env x
  58.  
  59. infer type_env (App m n) t (a:vars) = e1_result ++ e2_result where
  60.     e2_result = infer type_env n a vars new_name = (show a) ++ "_"
  61.     new_vars = genTypeVars new_name e1_result = infer type_env m
  62.     (ArrowType a t) new_vars
  63.  
  64. infer type_env (Fun x m) t (a:b:vars) = (Eq t (ArrowType a
  65.     b)):exp_result where exp_result = infer ((x,a):type_env) m b vars
  66.  
  67. -- Generates the constraints for certain type inferTypes type_env exp
  68. = infer type_env exp a vars where a = head (genTypeVars "a") vars =
  69. tail (genTypeVars "a")