The ListMacro.list
macro in list_macro.ex allows us to create match expressions on lists in which we can capture any elements we want and ignore others, without typing out long sequences of underscores.
For example, if we want to match the first and last element of a 12 element list, we can do this:
list([first, 10, last]) = Enum.to_list(1..12)
IO.inspect([first, last])
#=> [1, 12]
instead of this:
[first, _, _, _, _, _, _, _, _, _, _, last] = Enum.to_list(1..12)
IO.inspect([first, last])
#=> [1, 12]
Any combination of variables and numbers is allowed. And yes, it still works with pins, too:
pin_me = 3
list([a, b, ^pin_me, 2]) = [1, 2, 3, 4, 5]
IO.inspect([a, b])
#=> [1, 2]
list([a, b, ^pin_me, 2]) = [1, 2, 7, 4, 5]
** (MatchError) no match of right hand side value: [1, 2, 7, 4, 5]
We could use a variety of regex-like patterns to further refine the generated match expression. Whatever the case, this macro shows how to achieve the basic idea.
Thanks!