OCaml 编译器需要一个不相关的自定义类型

问题描述

type int_tree =
  | IntLeaf
  | IntNode of int * int option * int_tree * int_tree * int_tree 

let empty_int_tree = IntLeaf

let rec int_insert x t = match t with
  IntLeaf -> (x,None,IntLeaf,IntLeaf) |
  IntNode(a,c,d,e) -> if x<a then IntNode(x,Some a,e) else if x>a then IntNode(a,Some x,e) else t |
  IntNode(a,Some b,e) -> if x<a then IntNode(a,int_insert x c,e)
  else if x>a && x<b then IntNode(a,int_insert x d,e)
  else if x>b then IntNode(a,int_insert x e)
  else t

在上面的代码中,行

"IntNode(a,e) else t |"

抛出错误

Error: This expression has type int_tree
       but an expression was expected of type
         int * 'a option * int_tree * int_tree * int_tree

带有下划线的 IntNode(x,e) 部分。这个表达式应该是 int_tree 类型,并且函数返回一个 int_tree,那么为什么编译器需要“int * 'a option * int_tree * int_tree * int_tree”类型的东西?这甚至不是一种有意义的类型。如何阻止编译器将 a,b,e... 误解为泛型类型?通常你在 match 语句中编写类似 h::t 的东西是没有问题的,编译器知道 h 和 t 的含义。

解决方法

事实证明,解决方案就在我眼皮底下。第一行是错误的。它期望与第一行的类型相同,解决方案是在那里添加 IntNode 以使其成为

IntLeaf -> IntNode(x,None,IntLeaf,IntLeaf) |