Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ocaml pattern matching multiple elements in a list at once

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!

like image 271
chesspro Avatar asked Jan 23 '11 19:01

chesspro


People also ask

Are OCaml lists linked?

An OCaml list is a sequence of values all of which have the same type. They are implemented as singly-linked lists.


1 Answers

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)
  | _ -> []
like image 60
Niki Yoshiuchi Avatar answered Oct 10 '22 02:10

Niki Yoshiuchi