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