Flat
Usage Message: 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.
Attributes[Flat] = {Protected} Related Symbols: Attributes
ClearAttributes
Flatten
OneIdentity
SetAttributes
Notes: The Flat attribute has an effect both in evaluation an in pattern matching. In evaluation, the Flat attribute causes expressions to be flattened during evaluation. For example, if f has the attribute Flat, then f[f[1,2],3] will evaluate to f[1,2,3]:
In[1]:= Attributes[f] = Flat ;
In[2]:= f[f[1, 2], 3]
Out[2]= f[1, 2, 3]
The second effect of the Flat attribute is in pattern matching, where expressions for which the head has the Flat attribute are handling by grouping the elements in all possible combinations into subexpressions with that same head. For example, in matching the expression f[1,2,3], the pattern matcher will look for matches among the expressions f[f[1],f[2],f[3]], or f[f[1,2],f[3]], and so forth.
In[3]:= f[1, 2, 3] /. f[p_, q_] :> {p, q} /; Length[p] == 2
Out[3]= {f[1, 2], f[3]}
A related attribute is OneIdentity
. In pattern matching, if a symbol f has both the Flat attribute and the OneIdentity
attribute, then individual elements in an expression with a head of f will be considered without enclosing them in an expression with a head of f. For example, in matching the expression f[1,2,3], the pattern matcher will look for matches among the expressions f[1,2,3], or f[f[1,2],3], and so forth.
In[4]:= Attributes[f] = {Flat, OneIdentity} ;
In[5]:= f[1, 2, 3] /. f[p_, q_] :> {p, q} /; Length[p] == 2
Out[5]= {f[1, 2], 3}
When using the Flat attribute there is the potential for infinite iteration if you introduce a rule that reverses the operations that are done automatically by the pattern matcher. For example, if f has the Flat attribute, the assignment f[p_]:=p will generate infinite iteration:
In[6]:= Attributes[f] = Flat;
In[7]:= f[p_] := p
In[8]:= f[1, 2]
$IterationLimit::itlim: Iteration limit of 4096 exceeded.
Out[8]= Hold[f[1, 2]]
In the example above, the Flat attribute causes f[1,2] to be treated like f[f[1,2]] for the purpose of pattern matching, which
matches the rule for f[p_]. Application of this rule causes f[f[1,2]] to be replaced by f[1,2], which leads to infinite iteration,
since this result is the same as the original expression. In this example, if f is used with only one argument, then infinite iteration can be
avoided by using both Flat and OneIdentity
. If f will be used with more than one argument, then some other approach is needed, possibly not involving the Flat attribute.
Additional Online Documentation:
Mathematica 3.0
http://documents.wolfram.com/v3/RefGuide/Flat.html
Mathematica 4.0
http://documents.wolfram.com/v4/RefGuide/Flat.html
Questions or comments? Send email to support@wolfram.com.
| |