compiler-errors - Ocaml-匹配两个列表

标签 compiler-errors ocaml type-inference operator-precedence

我正在尝试在OCaml中编写随机播放功能,但是类型推断存在问题。 Merlin告诉我l1l2'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 []
;;

最佳答案

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

有关OCaml中不同运算符的优先级和关联性,请参见this table

关于compiler-errors - Ocaml-匹配两个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53232312/

相关文章:

c# - “类型”的使用类似于变量(C#)

debugging - 如何在 Emacs 中跟踪 "failwith"错误?

int - OCaml 的最大整数值

scala - 具有上限的函数中类型推断的奇怪行为

c# - 通用扩展方法中的额外通用参数?

java - 类型不匹配 : cannot convert from double to Double

c++ - 错误: C++ requires a type specifier for all declarations

c++ - 通过迭代器更改集合中的元素

ocaml - 为什么 int32s/int64s 比 int 慢?

typescript - 传递给通用函数包装器(如 _.debounce)的函数的类型推断