[英]Hindley Milner Type Inference in F#
Can somebody explain step by step type inference in following F# program: 有人可以在下面的F#程序中解释一步一步的类型推断:
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. 我特别希望逐步了解Hindley Milner的统一过程是如何运作的。
Fun stuff! 好玩的东西!
First we invent a generic type for sumList: x -> y
首先,我们为sumList创建一个泛型类型:
x -> y
And get the simple equations: t(lst) = x
; 得到简单的方程式:
t(lst) = x
; t(match ...) = y
Now you add the equation: t(lst) = [a]
because of (match lst with [] ...)
现在你添加等式:
t(lst) = [a]
因为(match lst with [] ...)
Then the equation: b = t(0) = Int
; 然后是等式:
b = t(0) = Int
; y = b
Since 0 is a possible result of the match: c = t(match lst with ...) = b
由于0是匹配的可能结果:
c = t(match lst with ...) = b
From the second pattern: t(lst) = [d]
; 从第二种模式:
t(lst) = [d]
; t(hd) = e
; t(hd) = e
; t(tl) = f
; t(tl) = f
; f = [e]
; f = [e]
; t(lst) = t(tl)
; t(lst) = t(tl)
; t(lst) = [t(hd)]
Guess a type (a generic type) for hd
: g = t(hd)
; 猜一下
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)
然后我们需要一个
sumList
类型,所以我们现在只得到一个没有意义的函数类型: h -> i = t(sumList)
So now we know: h = f
; 所以我们现在知道:
h = f
; t(sumList tl) = i
Then from the addition we get: Addable g
; 然后从添加我们得到:可
Addable g
; Addable i
; Addable i
; g = i
; g = i
; t(hd + sumList tl) = g
Now we can start unification: 现在我们可以开始统一了:
t(lst) = t(tl)
=>
[a] = f = [e]
=>
a = e
t(lst) = t(tl)
=>
[a] = f = [e]
=>
a = e
t(lst) = x = [a] = f = [e]
; t(lst) = x = [a] = f = [e]
; h = t(tl) = x
t(hd) = g = i
/\\
i = y
=>
y = t(hd)
t(hd) = g = i
/\\
i = y
=>
y = t(hd)
x = t(lst) = [t(hd)]
/\\
t(hd) = y
=>
x = [y]
x = t(lst) = [t(hd)]
/\\
t(hd) = y
=>
x = [y]
y = b = Int
/\\
x = [y]
=>
x = [Int]
=>
t(sumList) = [Int] -> Int
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. 我跳过了一些微不足道的步骤,但我认为你可以得到它的工作原理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.