Erlang - Pattern Matching



Patterns look the same as terms – they can be simple literals like atoms and numbers, compound like tuples and lists, or a mixture of both. They can also contain variables, which are alphanumeric strings that begin with a capital letter or underscore. A special "anonymous variable", _ (the underscore) is used when you don't care about the value to be matched, and won't be using it.

A pattern matches if it has the same "shape" as the term being matched, and atoms encountered are the same. For example, the following matches succeed −

  • B = 1.
  • 2 = 2.
  • {ok, C} = {ok, 40}.
  • [H|T] = [1, 2, 3,4].

Note that in the fourth example, the pipe (|) signifying the head and tail of the list as described in Terms. Also note that the left hand side should match the right hand side which is the normal case for patterns.

The following examples of pattern matching will fail.

  • 1 = 2.
  • {ok, A} = {failure, "Don't know the question"}.
  • [H|T] = [].

In the case of the pattern-matching operator, a failure generates an error and the process exits. How this can be trapped and handled is covered in Errors. Patterns are used to select which clause of a function will be executed.

Advertisements