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!
An OCaml list is a sequence of values all of which have the same type. They are implemented as singly-linked lists.
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)
| _ -> []
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With