Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hindley Milner Type Inference in F#

Can somebody explain step by step type inference in following F# program:

let rec sumList lst =
    match lst with
    | [] -> 0
    | hd :: tl -> hd + sumList tl

I specifically want to see step by step how process of unification in Hindley Milner works.

like image 713
hrishikeshp19 Avatar asked Dec 06 '11 07:12

hrishikeshp19


1 Answers

Fun stuff!

First we invent a generic type for sumList: x -> y

And get the simple equations: t(lst) = x; t(match ...) = y

Now you add the equation: t(lst) = [a] because of (match lst with [] ...)

Then the equation: b = t(0) = Int; y = b

Since 0 is a possible result of the match: c = t(match lst with ...) = b

From the second pattern: t(lst) = [d]; t(hd) = e; t(tl) = f; f = [e]; t(lst) = t(tl); t(lst) = [t(hd)]

Guess a type (a generic type) for hd: g = t(hd); e = g

Then we need a type for sumList, so we'll just get a meaningless function type for now: h -> i = t(sumList)

So now we know: h = f; t(sumList tl) = i

Then from the addition we get: Addable g; Addable i; g = i; t(hd + sumList tl) = g

Now we can start unification:

t(lst) = t(tl) => [a] = f = [e] => a = e

t(lst) = x = [a] = f = [e]; h = t(tl) = x

t(hd) = g = i /\ i = y => y = t(hd)

x = t(lst) = [t(hd)] /\ t(hd) = y => x = [y]

y = b = Int /\ x = [y] => x = [Int] => t(sumList) = [Int] -> Int

I skipped some trivial steps, but I think you can get how it works.

like image 124
Ramon Snir Avatar answered Sep 21 '22 14:09

Ramon Snir