Ocaml:此表达式的类型为'a list *'a list->布尔值,但期望表达为布尔值类型 [英] Ocaml: This expression has type 'a list * 'a list -> bool but an expression was expected of type bool

查看:95
本文介绍了Ocaml:此表达式的类型为'a list *'a list->布尔值,但期望表达为布尔值类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始学习Ocaml,并且正在使用递归函数. Ocaml编译器告诉我,在如果h1 = h2则帮助程序t1 t2"中递归调用helper会导致错误:此表达式的类型为'a list *'a list-> bool,但是期望表达式为bool类型.我知道这是在告诉我编译器期望一个布尔值,但是却得到了一个返回布尔值的函数.但是我不知道该如何解决.感谢您的帮助

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

推荐答案

您的定义let rec helper tmp l1 = function ...定义了一个函数helper,该函数带有三个参数:tmpl1用于模式匹配的匿名参数.这是因为function关键字引入了一个附加参数,它不是并不意味着在先前参数上有模式错误.

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.

您似乎想在tmpl1上进行匹配.在这种情况下,您可以编写let rec helper tmp l1 = match tmp, l1 with ....您也可以编写let rec helper = function ...,但是定义了一个接受 pair 的函数,因此您必须将其称为helper (t1, t2)helper ([], l)等.

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.

您还需要在[h2]@l1周围加上括号.请注意,更惯用的书写方式是h2::l1,但是您仍然需要括号.最后,OCaml将警告您,没有任何模式([], _::_)的情况.

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 ([], _::_).

这篇关于Ocaml:此表达式的类型为'a list *'a list->布尔值,但期望表达为布尔值类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆