Ocaml pattern matching multiple elements in a list at once

chesspro picture chesspro · Jan 23, 2011 · Viewed 7.6k times · Source

Lets say I have a list of type integer [1; 2; 3; 4; 5; 6; 7; 8] and I want to pattern match the first three elements at once. Is there any way to do this without nested match statements?

for example, can it be done like this?

let rec f (x: int list) : (int list) = 
begin match x with
| [] -> []
| [a; b; c]::rest -> (blah blah blah rest of the code here)
end

I could use the long nested method, which would be:

let rec f (x: int list) : (int list) =
begin match x with
| [] -> []
| h1::t1 ->
  begin match t1 with
  | [] -> []
  | h2::t2 ->
     begin match t2 with
     | [] -> []
     | t3:: h3 ->
        (rest of the code here)
     end
  end
end

Thanks!

Answer

Niki Yoshiuchi picture Niki Yoshiuchi · Jan 23, 2011

Yes, you can do that. The syntax is like this:

let rec f (x: int list) : (int list) = 
begin match x with
| [] -> []
| a::b::c::rest -> (blah blah blah rest of the code here)
end

but you'll notice that this will fail if the list has fewer than three elements. You can either add cases for single and two element lists, or just add a case that matches anything:

let rec f (x: int list) : (int list) = 
  match x with
  | a::b::c::rest -> (blah blah blah rest of the code here)
  | _ -> []