首页 > 解决方案 > Ocaml - 匹配两个列表

问题描述

我正在尝试在 OCaml 中编写一个 shuffle 函数,但是类型推断存在问题。Merlin 告诉我l1andl2是类型'a list list,这不是真的,因为它们只是'a list. 为什么它声称?

let shuffle l1 l2 =
  let rec scan l1 l2 acc =
    match (l1, l2) with
    | [],[] -> acc
    | ([],h2::t2) -> scan [] t2 h2::acc
    | (h1::t1, []) -> scan t1 [] h1::acc
    | (h1::t1,h2::t2) -> scan t1 t2 h1::h2::acc
  in scan l1 l2 []
;;

标签: compiler-errorsocamltype-inferenceoperator-precedence

解决方案


根本原因是运算符优先级不是由您按空格分组的。也就是说,scan [] t2 h2::acc被解释为(scan [] t2 h2)::acc, not scan [] t2 (h2::acc),因为函数应用的优先级高于::。解决方法是在适当的地方添加括号。

有关OCaml 中不同运算符的优先级和关联性,请参阅此表。


推荐阅读