Ocaml: This expression has type 'a list * 'a list -> bool but an expression was expected of type bool

邮差的信 提交于 2019-12-25 04:54:13

问题


I just started learning Ocaml and am playing around with recursive functions. Ocaml Compiler is telling me that recursively calling helper in "if h1=h2 then helper t1 t2" causes an error: This expression has type 'a list * 'a list -> bool but an expression was expected of type bool. I understand that it is telling me that the compiler is expecting a boolean but instead gets a function that returns the boolean. But I have no idea how I can fix this. Any help is appreciated

let rec a_func l =
  let rec helper tmp l1 = function
      | [], [] -> true
      | _, [] -> false
      | h1::t1, h2::t2 -> if h1=h2 then helper t1 t2 else helper [h2]@l1 t2
  in helper [] l

回答1:


Your definition let rec helper tmp l1 = function ... defines a function helper which takes three arguments: tmp, l1, and an anonymous argument which is used in the pattern match. This is because the function keyword introduces an additional argument, it does not mean a pattern mantch on previous arguments.

It looks like you want to match on tmp and l1. In that case, you can write let rec helper tmp l1 = match tmp, l1 with .... You can also write let rec helper = function ..., but that defines a function that takes a pair, so you would have to call it as helper (t1, t2), helper ([], l) etc.

You will also need to put parentheses around [h2]@l1. Note that a more idiomatic way of writing this is h2::l1, but you will still need the parentheses. Finally, OCaml will warn you that you have no case for the pattern ([], _::_).



来源:https://stackoverflow.com/questions/42201312/ocaml-this-expression-has-type-a-list-a-list-bool-but-an-expression-was

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!