Hindley Milner Type Inference in F#

前端 未结 1 2113
一个人的身影
一个人的身影 2021-02-15 16:32

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

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


        
1条回答
  •  别那么骄傲
    2021-02-15 16:54

    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.

    0 讨论(0)
提交回复
热议问题