练习是在ML中编写一个从二叉搜索树中删除元素的函数。 这是代码:
datatype 'a tree = Lf | Br of 'a * 'a tree * 'a tree;
fun deleteTop (Br(_, Lf, t2)) = t2
| deleteTop (Br(_, t1, Lf)) = t1
| deleteTop (Br(_, Br(v, u1, u2), t2)) =
Br(v, deleteTop (Br(v, u1, u2)), t2);
fun delete (Lf, k : string) = Lf
| delete (Br((a,b),t1,t2), k) =
if a=k then deleteTop(Br((a,b),t1,t2))
else if k<a then Br((a,b),delete(t1,k),t2)
else Br((a,b),t1,delete(t2,k));
当我将它加载到Poly / ML时,它警告我在deleteTop中不完整的模式匹配,但这并不重要,因为删除只会传递deleteTop一个分支。
val deleteTop = fn: 'a tree -> 'a tree
val delete = fn: (string * 'a) tree * string -> (string * 'a) tree
我创建了一个(string * int)树并运行了
> delete(a,"they");
Error-Type error in function application.
Function: delete : (string * 'a) tree * string -> (string * 'a) tree
Argument: (a, "they") : (string * int) tree * string
Reason:
Can't unify (string * 'a) tree with (string * int) tree
(Different type constructors)
Found near delete (a, "they")
Static Errors
让我重复其中一行:
Can't unify (string * 'a) tree with (string * int) tree
为什么ML不能统一&#39; a用int?
答案 0 :(得分:1)
如果您已定义 a ,则可以在顶层重新定义树和删除,从而获得类似的消息。它抱怨 a 中的树与 delete 中的树不同。
例如
> datatype 'a t = T of 'a;
datatype 'a t = T of 'a
> val x = T 1;
val x = T 1: int t
> datatype 'a t = T of 'a;
datatype 'a t = T of 'a
> val T y = x;
Pattern and expression have incompatible types.
Pattern: T y : 'a t
Expression: x : int t
Reason: Can't unify 'a t with int t (Different type constructors)
Found near val T y = x
Static Errors
>