Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way that we can reference the whole variable while in pattern matching of Elixir?

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?

like image 444
Noah Blues Avatar asked Jan 04 '14 12:01

Noah Blues


1 Answers

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

def foo(list = [h|t]), do: list ++ h
like image 145
Peter Minten Avatar answered Oct 27 '22 19:10

Peter Minten