[英]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.