Kayla Song
Kayla Song

Reputation: 89

OCaml matching tuples? Why is this match case unused?

I have the following bit of code in OCaml:

let matchElement x y= 
  match x with 
    | (y,_) -> true 
    | _ -> false;;

and I'm getting a warning that the case _ will always be unused.

My intention was that if x matches a tuple where the first element is equal to type y, then it returns true, otherwise, it returns false. Do you know how to do this?

Upvotes: 1

Views: 161

Answers (1)

Artyer
Artyer

Reputation: 40826

y is actually the new name for what it is matched with, which happens to be the same name as y. It is equivalent to:

let matchElement x y = 
  match x with 
    | (z, _) -> true (* A completely unrelated binding *)
    | _ -> false;;

Where you can see that all values of x match with the first pattern.

To do what you want to do, you can write this:

let matchElement x y =
    match x with
    | (y', _) when y' = y -> true
    | _ -> false

(* Or equivalently *)
let matchElement (x, _) y = x = y

Upvotes: 4

Related Questions