Compiler errors Ocaml-匹配两个列表
我试图用OCaml编写一个洗牌函数,但是类型推断有问题。梅林告诉我,Compiler errors Ocaml-匹配两个列表,compiler-errors,ocaml,type-inference,operator-precedence,Compiler Errors,Ocaml,Type Inference,Operator Precedence,我试图用OCaml编写一个洗牌函数,但是类型推断有问题。梅林告诉我,l1和l2属于'列表类型,这是不正确的,因为它们只是'列表。为什么会这样说 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::ac
l1
和l2
属于'列表类型,这是不正确的,因为它们只是'列表
。为什么会这样说
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[]t2h2::acc
被解释为(scan[]t2h2)::acc
,而不是scan[]t2(h2::acc)
,因为函数应用程序的优先级高于:
。解决方法就是在适当的地方添加括号
有关OCaml中不同运算符的优先级和关联性,请参见