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!
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)
| _ -> []
精彩评论