Pattern Matching Again

To round off this chapter, we’ll go back to pattern matching one more time.

The following table has some examples of patterns and terms; all the variables in the patterns are assumed unbound. A term is just an Erlang data structure. The third column of the table, marked Result, shows whether the pattern matched the term and, if so, the variable bindings that were created. Read through the examples, and make sure you really understand them.

Pattern

=

Term

Result

{X,abc}

=

{123,abc}

Succeeds with X = 123

{X,Y,Z}

=

{222,def,"cat"}

Succeeds with X = 222, Y = def, and Z = "cat"

{X,Y}

=

{333,ghi,"cat"}

Fails—the tuples have different shapes

X

=

true

Succeeds with X = true

{X,Y,X}

=

{{abc,12},42,{abc,12}}

Succeeds with X = {abc,12} and Y = 42

{X,Y,X} ...

Get Programming Erlang, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.