相同的let绑定导致不同的编译结果

时间:2019-03-01 04:01:24

标签: ocaml

type 'a tree =
    | Leaf of 'a
    | Node of 'a * 'a tree * 'a tree 

let rec foldtree init op = function
    | Leaf c -> op c init init
    | Node (c, l, r) -> op c (foldtree init op l) (foldtree init op r)

let size' = foldtree 0 (fun _ l r -> 1 + l + r)  (* this compiles fine *)
let size'' = foldtree 0 (fun _ l r -> 1 + l + r) (* this doesn't *)

在上面的OCaml代码中,size'size''的定义是相同的,但后者会导致编译错误:

Error: The type of this expression, '_weak1 tree -> int,
       contains type variables that cannot be generalized

1 个答案:

答案 0 :(得分:0)

它们都应该编译失败,因为它们都包含弱类型变量。但是,编译器一次只会报告一个致命错误。

偶然地,您通常可以通过eta-expansion来解决此问题:

let size tree = foldtree 0 (fun _ l r -> 1 + l + r) tree