tuplesmatchocaml

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?


Solution

  • 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