satoru
satoru

Reputation: 33235

How to match a pattern and a part of it at the same time in OCaml?

I'm working on an exercise that requires me to compare the first and second element of a list, and then I need to make a recursion call on the tail.

If I use h::t then I can't access the second element, while using first::second::t makes it harder to access the original tail.

Is there any syntax I can use to match both at the same time?

Upvotes: 3

Views: 87

Answers (1)

coredump
coredump

Reputation: 38967

You can use as to bind a pattern or a part of it to a variable, this is known as an alias pattern, for reference this is described in chapter 7. Patterns of the manual (https://ocaml.org/manual/)

* match [0;1;2] with 
| x::(y::t as s) -> (x,y,t,s) 
| _ -> failwith "no";

- : int * int * int list * int list = (0, 1, [2], [1; 2])

Upvotes: 4

Related Questions