为什么 ocaml 推断 bool 类型?
Why ocaml infers bool type?
我有以下定义:
type 'a tree = Leaf | Node of 'a * 'a tree * 'a tree
和函数
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, b), `Success(c, d)) -> if b < x < c then `Success(a, d) else `Failure
根据我的直觉,类型签名应该与注释中的一样,但 ocaml 将其推断为:
bool tree -> [ `Empty | `Failure | `Success of bool * bool ]
为什么会发生这种情况,是否可以解决?
看起来 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
.
问题是b < x < c
。它被解释为 (b < x) < c
,并且由于 <
returns 一个 bool
并且要求两个操作数的类型相同,所以 c
也必须是一个 bool
.
你想要的是 b < x && x < c
.
我有以下定义:
type 'a tree = Leaf | Node of 'a * 'a tree * 'a tree
和函数
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, b), `Success(c, d)) -> if b < x < c then `Success(a, d) else `Failure
根据我的直觉,类型签名应该与注释中的一样,但 ocaml 将其推断为:
bool tree -> [ `Empty | `Failure | `Success of bool * bool ]
为什么会发生这种情况,是否可以解决?
看起来 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
.
问题是b < x < c
。它被解释为 (b < x) < c
,并且由于 <
returns 一个 bool
并且要求两个操作数的类型相同,所以 c
也必须是一个 bool
.
你想要的是 b < x && x < c
.