Reputation: 13
I want to count how many "u"s are in a list. An example of the function call would be
countu(["u"; "a"; "x"], 0);;
:-int = 1
The code I have is
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);;
I understand why I'm getting the problem. Ocaml wants a 'a list, but because I am comparing it to a string, it makes it a string. It will also get mad when I recall countu with y+1, because again, it wants a non-specified unit instead of an integer. How do I get around this. I want the signature to look like
val countups : string list * int -> int = <fun>
Upvotes: 1
Views: 2858
Reputation: 66818
You have:
if List.length (List.hd x) == 0 then ...
But this only makes sense if x
is a list of lists. Your x
is a list of strings.
Possibly what you want is just this:
if List.length x = 0 then ...
As a side comment, the equality comparison operator in OCaml is =
. The ==
operator is for special cases, and you shouldn't use it without having a good reason.
Upvotes: 1