Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the pattern [_|_] in Erlang mean anything specific?

Tags:

erlang

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 image 787
toraritte Avatar asked Jun 21 '15 05:06

toraritte


People also ask

How does pattern matching work in Erlang?

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.

What is assignment in Erlang programming language?

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.

What is a pattern matching error?

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.

What is pattern matching in Python?

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.


1 Answers

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.

like image 154
sepp2k Avatar answered Oct 26 '22 05:10

sepp2k