A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from http://www.erlang.org/doc/apps/erts/match_spec below:

Match Specifications in Erlang — erts v16.0.1

A "match specification" (match_spec) is an Erlang term describing a small "program" that tries to match something. It can be used to either control tracing with erlang:trace_pattern/3 or to search for objects in an ETS table with for example ets:select/2. The match specification in many ways works like a small function in Erlang, but is interpreted/compiled by the Erlang runtime system to something much more efficient than calling an Erlang function. The match specification is also very limited compared to the expressiveness of real Erlang functions.

The most notable difference between a match specification and an Erlang fun is the syntax. Match specifications are Erlang terms, not Erlang code. Also, a match specification has a strange concept of exceptions:

Grammar

A match specification used in tracing can be described in the following informal grammar:

A match specification used in ets can be described in the following informal grammar:

Function Descriptions Functions Allowed in All Types of Match Specifications

The functions allowed in match_spec work as follows:

Functions Allowed Only for Tracing

The functions allowed only for tracing work as follows:

Note

All "function calls" must be tuples, even if they take no arguments. The value of self is the atom() self, but the value of {self} is the pid() of the current process.

Match target

Each execution of a match specification is done against a match target term. The format and content of the target term depends on the context in which the match is done. The match target for ETS is always a full table tuple. The match target for call trace is always a list of all function arguments. The match target for event trace depends on the event type, see table below.

Context Type Match target Description ETS {Key, Value1, Value2, ...} A table object Trace call [Arg1, Arg2, ...] Function arguments Trace send [Receiver, Message] Receiving process/port and message term Trace 'receive' [Node, Sender, Message] Sending node, process/port and message term

Table: Match target depending on context

Variables and Literals

Variables take the form '$<number>', where <number> is an integer between 0 and 100,000,000 (1e+8). The behavior if the number is outside these limits is undefined. In the MatchHead part, the special variable '_' matches anything, and never gets bound (like _ in Erlang).

In the MatchHead part, all literals (except the variables above) are interpreted "as is".

In the MatchCondition/MatchBody parts, the interpretation is in some ways different. Literals in these parts can either be written "as is", which works for all literals except tuples, or by using the special form {const, T}, where T is any Erlang term.

For tuple literals in the match specification, double tuple parentheses can also be used, that is, construct them as a tuple of arity one containing a single tuple, which is the one to be constructed. The "double tuple parenthesis" syntax is useful to construct tuples from already bound variables, like in {{'$1', [a,b,'$2']}}. Examples:

Expression Variable Bindings Result {{'$1','$2'}} '$1' = a, '$2' = b {a,b} {const, {'$1', '$2'}} Irrelevant {'$1', '$2'} a Irrelevant a '$1' '$1' = [] [] [{{a}}] Irrelevant [{a}] ['$1'] '$1' = [] [[]] 42 Irrelevant 42 "hello" Irrelevant "hello" $1 Irrelevant 49 (the ASCII value for character '1')

Table: Literals in MatchCondition/MatchBody Parts of a Match Specification

Execution of the Match

The execution of the match expression, when the runtime system decides whether a trace message is to be sent, is as follows:

For each tuple in the MatchExpression list and while no match has succeeded:

  1. Match the MatchHead part against the match target term, binding the '$<number>' variables (much like in ets:match/2). If the MatchHead part cannot match the arguments, the match fails.
  2. Evaluate each MatchCondition (where only '$<number>' variables previously bound in the MatchHead part can occur) and expect it to return the atom true. When a condition does not evaluate to true, the match fails. If any BIF call generates an exception, the match also fails.
  3. Two cases can occur:
Differences between Match Specifications in ETS and Tracing

ETS match specifications produce a return value. Usually the MatchBody contains one single ConditionExpression that defines the return value without any side effects. Calls with side effects are not allowed in the ETS context.

When tracing there is no return value to produce, the match specification either matches or does not. The effect when the expression matches is a trace message rather than a returned term. The ActionTerms are executed as in an imperative language, that is, for their side effects. Functions with side effects are also allowed when tracing.

Tracing Examples

Match an argument list of three, where the first and third arguments are equal:

[{['$1', '_', '$1'],
  [],
  []}]

Match an argument list of three, where the second argument is a number > 3:

[{['_', '$1', '_'],
  [{ '>', '$1', 3}],
  []}]

Match an argument list of three, where the third argument is either a tuple containing argument one and two, or a list beginning with argument one and two (that is, [a,b,[a,b,c]] or [a,b,{a,b}]):

[{['$1', '$2', '$3'],
  [{'orelse',
      {'=:=', '$3', {{'$1','$2'}}},
      {'and',
        {'=:=', '$1', {hd, '$3'}},
        {'=:=', '$2', {hd, {tl, '$3'}}}}}],
  []}]

The above problem can also be solved as follows:

[{['$1', '$2', {'$1', '$2}], [], []},
 {['$1', '$2', ['$1', '$2' | '_']], [], []}]

Match two arguments, where the first is a tuple beginning with a list that in turn begins with the second argument times two (that is, [{[4,x],y},2] or [{[8], y, z},4]):

[{['$1', '$2'],[{'=:=', {'*', 2, '$2'}, {hd, {element, 1, '$1'}}}],
  []}]

Match three arguments. When all three are equal and are numbers, append the process dump to the trace message, otherwise let the trace message be "as is", but set the sequential trace token label to 4711:

[{['$1', '$1', '$1'],
  [{is_number, '$1'}],
  [{message, {process_dump}}]},
 {'_', [], [{set_seq_token, label, 4711}]}]

As can be noted above, the parameter list can be matched against a single MatchVariable or an '_'. To replace the whole parameter list with a single variable is a special case. In all other cases the MatchHead must be a proper list.

Generate a trace message only if the trace control word is set to 1:

[{'_',
  [{'==',{get_tcw},{const, 1}}],
  []}]

Generate a trace message only if there is a seq_trace token:

[{'_',
  [{'==',{is_seq_trace},{const, 1}}],
  []}]

Remove the 'silent' trace flag when the first argument is 'verbose', and add it when it is 'silent':

[{'$1',
  [{'==',{hd, '$1'},verbose}],
  [{trace, [silent],[]}]},
 {'$1',
  [{'==',{hd, '$1'},silent}],
  [{trace, [],[silent]}]}]

Add a return_trace message if the function is of arity 3:

[{'$1',
  [{'==',{length, '$1'},3}],
  [{return_trace}]},
 {'_',[],[]}]

Generate a trace message only if the function is of arity 3 and the first argument is 'trace':

[{['trace','$2','$3'],
  [],
  []},
 {'_',[],[]}]
ETS Examples

Match all objects in an ETS table, where the first element is the atom 'strider' and the tuple arity is 3, and return the whole object:

[{{strider,'_','_'},
  [],
  ['$_']}]

Match all objects in an ETS table with arity > 1 and the first element is 'gandalf', and return element 2:

[{'$1',
  [{'==', gandalf, {element, 1, '$1'}},{'>=',{size, '$1'},2}],
  [{element,2,'$1'}]}]

In this example, if the first element had been the key, it is much more efficient to match that key in the MatchHead part than in the MatchConditions part. The search space of the tables is restricted with regards to the MatchHead so that only objects with the matching key are searched.

Match tuples of three elements, where the second element is either 'merry' or 'pippin', and return the whole objects:

[{{'_',merry,'_'},
  [],
  ['$_']},
 {{'_',pippin,'_'},
  [],
  ['$_']}]

Function ets:test_ms/2 can be useful for testing complicated ETS matches.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4