sdiehl / write-you-a-haskell

Building a modern functional compiler from first principles. (http://dev.stephendiehl.com/fun/)
MIT License
3.34k stars 256 forks source link

poly: infer - a new approach #37

Closed chsievers closed 9 years ago

chsievers commented 9 years ago

Maybe you like this version better. You'll surely need the first commit.

sdiehl commented 9 years ago

This is very good, the other approach worked but special cased the operators If/Op/Fix which wasn't as simple for the exposition. This uses the same approach for all syntax terms, which is great.

So this builds up the composition substitution tf by folding the intermediate substitution over each term in a list of subexpressions. I'll just have to figure out how to change the text of the tutorial to describe it.

inferPrim :: TypeEnv -> [Expr] -> Type -> Infer (Subst, Type)
inferPrim env l t = do
  tv <- fresh
  (s1, tf) <- foldM inferStep (nullSubst, id) l
  s2 <- unify (tf tv) t
  return (s2 `compose` s1, apply s2 tv)

  where inferStep (s, tf) exp = do 
          (s', t) <- infer (apply s env) exp
          return (s' `compose` s, tf . (TArr t))