此表达式具有 bool 类型,但表达式应为 unit 类型,因为它是条件语句的结果,没有 else 分支

This expression has type bool but an expression was expected of type unit because it is in the result of a conditional with no else branch

感谢您阅读这个问题。在我的 OCaml 代码中,我编写了一个函数来从我的 heap list:

中检索最大值 object_
type object_ = int;;

let rec get_current_heap_max_object (heap1:heap) (acc:object_) = 
  match heap1 with 
  | [] -> acc 
  | hd :: tl -> 
    match hd with 
    | ((obj1, field1), tva1) -> 
      (if acc < obj1 then 
         acc = obj1; 
         get_current_heap_max_object tl acc 
       else 
         get_current_heap_max_object tl acc)

错误在 acc = obj1; 为:

This expression has type bool but an expression was expected of type unit because it is in the result of a conditional with no else branch

表达式中

if acc < obj1 then acc = obj1

子表达式 acc = obj1 正在测试 accobj1 是否相等,而不是为变量 acc 赋值(OCaml 默认情况下变量是不可变的).由于 then 分支返回布尔值,因此您不能省略 else 分支。 您可以重写代码以避免依赖可变性,方法是定义一个新的 max 变量,该变量可以是 accobj1:

let max = if acc < obj1 then ... else ... in
get_current_heap_max_object tl max