I am learning Erlang from Learn You Some Erlang and I've seen the pattern [_|_]
twice already but couldn't find any info on it. This usage seems superfluous because omitting it from (1) and subsituting it with _ in (2) yields the same result without degrading readability. It is my first week with Erlang so I may be completely wrong.
(1) from bestest_qsort:
bestest_qsort(L=[_|_]) ->
bestest_qsort(L, []).
(2) from here:
error:{badmatch,[_|_]} -> ok
Like many other functional languages, Erlang has powerful pattern matching capabilities. Typically, a pattern (left side) is matched against a term (right side). Pattern matching can also occur in receive blocks, in which case the pattern is matched against the existing messages in a process queue.
There is nothing like an assignment in Erlang programming language; there is a different approach to accessing values in memory, which is the pattern-matching operations.
In a pattern matching, a left-hand side pattern is matched against a right-hand side term. If the matching succeeds, any unbound variables in the pattern become bound. If the matching fails, a run-time error occurs.
Pattern matching occurs when evaluating a function call, case - receive - try - expressions and match operator (=) expressions. In a pattern matching, a left-hand side pattern is matched against a right-hand side term.
The pattern [p1 | p2]
matches a non-empty list, whose head matches the pattern p1
and whose tail matches the pattern p2
. So since the pattern _
matches anything, [_ | _]
matches any non-empty list.
_
by itself on the other hand matches anything, including the empty list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With