简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM