HM inference examples
let-inference
https://stackoverflow.com/questions/44509154/let-inference-in-hindley-milner?rq=1
ex = \a -> let b = a in b + 1
First, we associate
a
with a fresh type variable, saya :: t0
.Then we type
b = a
. We getb :: t0
as well.However, and this is the key point, we should not generalize the type of
b
tob :: forall t0. t0
. This is because we can only generalize over a tyvar which does not occur in the environment: here, instead, we do havet0
in the environment sincea :: t0
is there.If you do generalize it, you will get a way too general type for
b
; thenb + 1
becomesb+1 :: forall t0. Num t0 => t0
, and the whole term getsforall t0 t1. Num t1 => t0 -> t1
since the types fora
andb
are unrelated (t0
, once generalized, can be alpha-converted tot1
).
a :: a
b :: b
(b = a) ->
b :: a
(b + 1) :: Num a ->
b :: Num a
ex ::
ex :: Num a => a -> a ex = \a -> let b = a in b + 1
ex :: Num a => a -> a ex a = let b = a in b + 1
ex :: Num a => a -> a ex a = a + 1
Last updated
Was this helpful?