Easiest pattern match for: first two elements of a list of at least two elements

yeah, the only thing I could come up with is:

[k | [v | _]]

is there an easier way? it’s not too bad for 2 elements, but shortly after that line of code, I have the 3-element version, and that really starts to get kind of ugly

3 Likes

There is something much easier:

iex(1)> [a, b|_] = [1,2,3]
[1, 2, 3]
iex(2)> a                 
1
iex(3)> b
2
iex(4)> [a, b|_] = []
** (MatchError) no match of right hand side value: []
7 Likes

ah, thanks, I see that I was complicating the syntax by incorrectly assuming a requirement for explicit nesting

2 Likes