值不匹配

Values do not match

我很确定我没有眯着眼睛看不匹配的地方......但我一直盯着我的屏幕很长时间,因此问了这个问题。

我的 MLI 文件看起来像

type ('k, 'v) t

val empty: ('k, 'v) t 

val find: 'k -> ('k, 'v) t -> 'v option

val bindings: ('k, 'v) t -> ('k * 'v) list

val insert: 'k -> 'v -> ('k, 'v) t -> ('k, 'v) t

并且我在我的 ML 文件中对每一个都有一个实现

type color = Red | Black
type ('k, 'v) t = Leaf | Node of (color * ('k, 'v) t * ('k * 'v) * ('k, 'v) t)

let empty = Leaf

let rec find k = function 
  | Leaf -> None
  | Node (_, l, (x, y), r) -> 
      if k < x then find k l
      else if k > x then find k r
      else Some y

let rec bindings = function 
  | Leaf -> []
  | Node (_, l, t, r) -> List.append (t :: bindings l) (bindings r)

let balance = function 
  | (Black, Node (Red, Node (Red, a, (xk, xv), b), (yk, yv), c), (zk, zv), d)
  | (Black, a, (xk, xv) ,Node (Red, b, (yk, yv), Node (Red, c, (zk, zv), d)))
  | (Black, Node (Red, a, (xk, xv), Node (Red, b, (yk, yv), c)), (zk, zv), d)
  | (Black, a, (xk, xv), Node (Red, Node (Red, b, (yk, yv), c), (zk, zv), d)) 
    -> Node (Red, Node (Black, a, (xk, xv), b), (yk, yv), Node (Black, c, (zk, zv), d))
  | t -> Node t

let rec insert_aux k v = function 
  | Leaf -> Node (Red, Leaf, (k, v), Leaf)
  | Node (c, l, (x, y), r) as n -> 
      if k < x then balance (c, insert_aux k v l, (x, y), r)
      else if k > v then balance (c, l, (x, y), insert_aux k v r)
      else n

let insert k v m = 
  match insert_aux k v m with 
  | Leaf -> failwith "Not possible"
  | Node (_, l, t, r) -> Node (Black, l, t, r)

如您所见,插入函数已实现,我可以看到它返回了正确的类型。但是当我这样做时 dune build 我从 ocaml 编译器

得到了以下错误
File "redblacktreemap/redBlackTreeMap.ml", line 1:
Error: The implementation redblacktreemap/redBlackTreeMap.ml
       does not match the interface redblacktreemap/.RedBlackTreeMap.objs/byte/redBlackTreeMap.cmi:
       Values do not match:
         val insert : 'a -> 'a -> ('a, 'a) t -> ('a, 'a) t
       is not included in
         val insert : 'k -> 'v -> ('k, 'v) t -> ('k, 'v) t
       File "redblacktreemap/redBlackTreeMap.mli", line 19, characters 0-48:
         Expected declaration
       File "redblacktreemap/redBlackTreeMap.ml", line 32, characters 4-10:
         Actual declaration

从错误类型 a -> 'a -> ('a, 'a) t -> ('a, 'a) t 可以看出,您的代码正在做一些事情,使编译器推断出键和值是同一类型。这不是您想要的——拥有两个类型参数 (k, v) 的全部原因是类型是独立的。

啊哈,你有这个子表达式:

k > v

这意味着kv必须是同一类型。

可能你的意思是 k > x