1
votes

I am new to OCaml, so I am learning the basics. I am writing a function that determines whether a list contains a given integer.

let rec int_member (x: int) (l: int list) : bool 
begin match l with
| [] -> false
| hd :: rest -> x = hd || int_member rest x
end

as a test case...

let test (): bool =
(int_member 1 [1;2;3]) = true
;; run_test "contains 1 [1;2;3]" test

I am getting an error saying that "this expression has type int list but an expression was expected of type int". How can I fix this?

2

2 Answers

3
votes

If you look at your recursive call, you should see that you're not passing the arguments quite right! Otherwise this code is quite good. (I see a missing =, and also using begin and end isn't very idiomatic OCaml here. You can just leave them out.)

1
votes

int_member rest x

The first argument to int_member should be an int. You're passing an int list as the first argument. That's what the error message is complaining about.

You simply switched around the order of the arguments.

PS: The begin ... end in your code is superfluous.