繼suggestion使用嵌套結構的遞歸數據類型就像樹一樣,我嘗試使所述rechaurive datatyep在測試程序中工作,但遇到(又一個,對我來說很神祕)錯誤。與遞歸數據類型的統一
我的計劃是這樣的:
datatype 'a tree =
Leaf of { value : 'a }
| Node of { value : 'a, left: 'a tree, right: 'a tree }
fun recursivetreebuilder a n =
if n = 0
then
Leaf a
else
Node (a, recursivetreebuilder(a, n-1), recursivetreebuilder(a, n-1))
因此,該功能應該構建深度n
的二叉樹,通過減少n
小號遞歸調用本身,直到n
爲0
但我我得到這個錯誤:
Can't unify {left: 'a tree, right: 'a tree, value: 'a} with {value: 'b} *
(Int32.int/int -> 'c) * (Int32.int/int -> 'c) (Field 1 missing) Found near if
<(n, 0) then Leaf(a) else Node(a, recursivetreebuilder(...), ......)
使用遞歸數據類型的目的是解決另一個統一的問題當使用嵌套列表時。也許我應該能夠看到問題的解釋給我的其他問題,但我還沒有。
編譯器引用什麼「字段1」?爲什麼遞歸數據類型旨在使其能夠統一同一數據類型的不同「子類型」,爲什麼不能統一?
編輯
嘗試了幾個建議的結構,但仍然出現錯誤。例如,對於
datatype 'a tree =
Leaf of 'a
| Node of 'a tree * 'a tree
fun recursivetreebuilder a n =
if n < 0
then
Leaf (a)
else
Node (recursivetreebuilder(a, n-1), recursivetreebuilder(a, n-1))
我得到
val printList = fn : Int.int list -> unit
Error- in 'recon_bintree.sml', line 12.
Can't unify 'a with 'a * Int32.int/int (Type variable to be unified occurs in type) Found near if
<(n, 0) then Leaf(a) else
Node(recursivetreebuilder(a, ...), recursivetreebuilder(...))
Error- in 'recon_bintree.sml', line 12.
Can't unify 'a with 'a * Int32.int/int (Type variable to be unified occurs in type) Found near if
<(n, 0) then Leaf(a) else
Node(recursivetreebuilder(a, ...), recursivetreebuilder(...))
Error- in 'recon_bintree.sml', line 12.
Can't unify 'a tree with Int32.int/int -> 'b (Incompatible types) Found near if
<(n, 0) then Leaf(a) else
Node(recursivetreebuilder(a, ...), recursivetreebuilder(...))
Error- in 'recon_bintree.sml', line 12.
Can't unify 'a tree with Int32.int/int -> 'b (Incompatible types) Found near if
<(n, 0) then Leaf(a) else
Node(recursivetreebuilder(a, ...), recursivetreebuilder(...))
Exception- Fail "Static errors (pass2)" raised
好吧,我明白......或多或少。我試着實現你的第二個建議結構,但我仍然得到統一錯誤......我在那裏錯過了什麼?我更新了這個問題。 –
@lotolmencre:對不起。你還有另一個問題,我沒有注意到。我現在已經更新了答案來解釋這兩個問題。 (這次我測試過了。) – ruakh
謝謝,現在已經變得更清楚了。 –