我刚开始学习Ocaml并且正在玩递归函数 . Ocaml编译器告诉我在“if h1 = h2 then helper t1 t2”中递归调用helper会导致错误:这个表达式的类型为'list *'列表 - > bool但是表达式的类型为bool . 我知道它告诉我编译器期望一个布尔值,而是获得一个返回布尔值的函数 . 但我不知道如何解决这个问题 . 任何帮助表示赞赏
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 回答
您的定义
let rec helper tmp l1 = function ...
定义了一个函数helper
,该函数有三个参数:tmp
,l1
,以及模式匹配中使用的匿名参数 . 这是因为function
关键字引入了另一个参数,它并不意味着先前参数的模式mantch .看起来你想匹配
tmp
和l1
. 在这种情况下,您可以编写let rec helper tmp l1 = match tmp, l1 with ...
. 您也可以编写let rec helper = function ...
,但是它定义了一对函数,因此您必须将其称为helper (t1, t2)
,helper ([], l)
等 .您还需要在
[h2]@l1
周围加上括号 . 请注意,更为惯用的写法是h2::l1
,但您仍需要括号 . 最后,OCaml会警告你,你没有案例([], _::_)
.