5

There is an as-pattern in Haskell, which allows us referencing the whole variable while in pattern matching:

foo wholeList@(head:tail) = wholeList ++ head

The variable wholeList represents the original variable.

Assuming that head is ["Hello"], and tail is ["World"], then wholeList is ["Hello", "World"].

Using as-pattern, we can avoid constructing the variable again by concatenating head and tail.

Does such feature exist in Elixir?

Noah Blues
  • 1,339
  • 2
  • 11
  • 19

1 Answers1

8

Yes, this is possible. Just use = in your pattern:

def foo(list = [h|t]), do: list ++ h
José Valim
  • 50,409
  • 12
  • 130
  • 115
Peter Minten
  • 136
  • 4