ris*_*p89 8 f# type-inference hindley-milner
有人可以在下面的F#程序中解释一步一步的类型推断:
let rec sumList lst =
match lst with
| [] -> 0
| hd :: tl -> hd + sumList tl
Run Code Online (Sandbox Code Playgroud)
我特别希望逐步了解Hindley Milner的统一过程是如何运作的.
Ram*_*nir 17
好玩的东西!
首先,我们为sumList创建一个泛型类型:
x -> y
并得到简单的公式:
t(lst) = x;
t(match ...) = y
现在你添加等式:
t(lst) = [a]因为(match lst with [] ...)
等式:
b = t(0) = Int;y = b
由于0是匹配的可能结果:
c = t(match lst with ...) = b
从第二图案:
t(lst) = [d];
t(hd) = e;
t(tl) = f;
f = [e];
t(lst) = t(tl);
t(lst) = [t(hd)]
猜测一个类型(通用型)hd:
g = t(hd);e = g
然后我们需要一个类型sumList,所以我们现在只得到一个无意义的函数类型:
h -> i = t(sumList)
所以现在我们知道:
h = f;
t(sumList tl) = i
然后从加法我们得到:
Addable g;
Addable i;
g = i;
t(hd + sumList tl) = g
现在我们可以开始统一了:
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
我跳过了一些微不足道的步骤,但我认为你可以了解它是如何工作的.