问题描述
我有以下定义:
new_dict = {"alex,jones" : "present","sam,junior" : "absent"}
和功能
type 'a tree = Leaf | Node of 'a * 'a tree * 'a tree
通过我的直觉类型签名应与注释中的相同,但ocaml会将其推断为:
let rec is_bst' (t: 'a tree) :[> `Empty | `Failure | `Success of 'a * 'a ]= match t with
| Leaf -> `Empty
| Node(x,l,r) -> match (is_bst' l,is_bst' r) with
| (`Failure,_) -> `Failure
| (_,`Failure) -> `Failure
| (`Empty,`Empty) -> `Empty
| (`Success(a,b),`Empty) -> if b < x then `Success(a,x) else `Failure
| (`Empty,`Success(a,b)) -> if x < a then `Success(x,b) else `Failure
| (`Success(a,`Success(c,d)) -> if b < x < c then `Success(a,d) else `Failure
为什么会发生这种情况,并且有可能解决?
解决方法
问题是b < x < c
。它被解释为(b < x) < c
,并且由于<
返回bool
并要求两个操作数的类型相同,因此c
也必须是bool
。
您想要的是b < x && x < c
。
b < x < c
要求c
为bool
:
# 4 < 7 < 9
_
;;
Error: This expression has type int but an expression was expected of type bool
在这里说9
应该是bool
。
所以c: bool
=> Success(c,d) == Success of bool * bool
。