我想知道列表中有多少“你”。函数调用的一个例子是
countu(["u"; "a"; "x"], 0);;
:-int = 1
我的代码是
let rec countu = fun(x, y) ->
if List.length (List.hd x) == 0 then y
else if List.hd x == "u" then countu(List.tl x, y+1)
else countu(List.tl x, y);;
我理解为什么我会遇到这个问题。 Ocaml想要一个'列表,但因为我将它与字符串进行比较,它使它成为一个字符串。当我用y + 1回忆countu时它也会生气,因为它再次需要一个非指定单位而不是一个整数。我该如何解决这个问题。我希望签名看起来像
val countups : string list * int -> int = <fun>
你有:
if List.length (List.hd x) == 0 then ...
但这只有在x
是列表清单时才有意义。你的x
是一个字符串列表。
可能你想要的只是这个:
if List.length x = 0 then ...
作为旁注,OCaml中的相等比较运算符是=
。 ==
操作符用于特殊情况,如果没有充分的理由,您不应该使用它。