Ocaml pattern matching multiple items in a list at once

Suppose I have a list of type integer [1; 2; 3; 4; 5; 6; 7; 8], and I want the template to match the first three elements at the same time. Is there a way to do this without nested matching operators?

for example, can this be done as follows?

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 a long nested method, which would be the following:

 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!

+8
matching design-patterns ocaml elements
source share
1 answer

Yes you can do it. The syntax is as follows:

 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 will notice that this will happen if the list contains less than three elements. You can either add cases for one or two lists of elements, or simply add a case that matches something:

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

Source: https://habr.com/ru/post/651416/


All Articles