Reputation: 175
I am new to OCaml and struggling to work with matches. I want to write a function that takes a list and a value and then returns true if the value is in that list and false if it is not. Here is my idea but I am struggling to get it to work.
let rec contains xs x =
match xs with
| [] -> false
| z :: zs ->
match x with
| z -> true
| _ -> contains zs x
Upvotes: 1
Views: 111
Reputation: 29106
When you use an identifier as a pattern, you will bind the value you match on to that identifier. I.e
match x with
| z -> true
will bind the value of x
to the name z
. You will also get a warning about z
and the _
branch being unused.
You also don't need a second pattern match since it can be folded into the first:
let rec contains xs x =
match xs with
| [] -> false
| z :: _ when z = x -> true
| _ :: zs -> contains zs x
Upvotes: 3