Flat

Flat

is an attribute that can be assigned to a symbol f to indicate that all expressions involving nested functions f should be flattened out. This property is accounted for in pattern matching.

Details

  • Flat corresponds to the mathematical property of associativity.
  • For a symbol f with attribute Flat, f[f[a,b],f[c]] is automatically reduced to f[a,b,c].
  • Functions like Plus, Times, and Dot are Flat.
  • For a Flat function f, the variables x and y in the pattern f[x_,y_] can correspond to any sequence of arguments.
  • The Flat attribute must be assigned before defining any values for a Flat function.

Examples

open allclose all

Basic Examples  (3)

Nested expressions with flat functions are flattened out:

Flat implements the notion of associativity:

Flat allows the pattern matcher to use associativity:

Scope  (3)

Nested expressions with associative functions are flattened out:

In pattern matching, Flat allows sequences of elements to be replaced:

For flat and orderless functions, any subset of the arguments may match:

Properties & Relations  (5)

Nested expressions with flat functions are automatically flattened:

For flat functions, a definition for the two-argument case is normally sufficient:

An expression with a flat head is considered matched in its entirety when any sequence is matched:

Compare with:

ReplaceRepeated may be helpful in ensuring all occurrences are replaced:

When Blank matches a sequence inside a Flat function f, it will maintain the head f:

Sequential patterns like BlankSequence and BlankNullSequence are not affected by Flat:

For a flat function f that is not OneIdentity, when f[x_] is compared with f[expr], the pattern matcher will attempt to bind x_ to f[expr] first, and only if that fails to expr:

If the function also has attribute OneIdentity, the first attempt is skipped:

Possible Issues  (4)

For flat and orderless functions, pattern matching may have to try a large number of cases:

Longest can be used to prevent additional matches for shorter subexpressions:

For a flat function f, the pattern f[_] matches f with one or more arguments:

Repeated can be used as a pattern that only matches a single argument, even inside a flat function:

Restrictions may behave unexpectedly because x_ matches together with the head of a flat function:

The following restriction works because x_Plus matches Plus[b,c]:

However, this one will fail because x_ cannot have both head Plus and Symbol:

Using BlankSequence on the left-hand-side produces more consistent results:

Introduced in 1988
 (1.0)