繁体   English   中英

F#中的Hindley Milner类型推断

[英]Hindley Milner Type Inference in F#

有人可以在下面的F#程序中解释一步一步的类型推断:

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

我特别希望逐步了解Hindley Milner的统一过程是如何运作的。

好玩的东西!

首先,我们为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

我跳过了一些微不足道的步骤,但我认为你可以得到它的工作原理。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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