Thursday, February 4, 2016

Wolfram Language Attribute: Flat

Attributes modify the behavior of entire classes of functions. Some Attributes cause functions to have well-known mathematical properties such as commutativity, associativity, or idempotency, notably for valid pattern-matching. Others control the way the Wolfram Language evaluates or does not evaluate a function's arguments, which if you study that you will see is at the very core of Wolfram Language operation.

Listable is a valuable functional language Attribute since it incorporates Thread into a function so it automatically maps over a List and instead of taking a List apart, we apply a function to it as a gestalt.

NumericFunction is an Attribute of all Wolfram Language mathematical functions and is True when all of their arguments are numerical. I suspect it is integral to the interaction of many functions with the underlying knowledge base of Mathematica and therefore to many functions' valid behavior (e.g. Piecewise – always define piecewise mathematical functions with Piecewise).

Attribute: Flat


Flat is the mathematical property of associativity, which dictates that different groupings of numbers to specify the order in which the operation is performed, return the same result. E.g. ((a+b)+c) = (a+(b+c)) and (2x3)x4 = 2x(3x4).

a+(b+c)==(a+b)+c

True

Thomas Bahder uses a neat trick to show how Attributes work and how some affect pattern-matching. Here is the trick revealing the mechanism of Flat. Bahder uses a Condition that will never be True, which causes Wolfram Language to try all permutations of the function's arguments that are valid under Orderless. In the false predicate he inserts a Print statement to reveal how the Wolfram Language evaluator works. HoldForm is necessary to stop the evaluator from putting the arguments into standard order before printing them.

Flat tells the Wolfram Language evaluator, 'If the given pattern x_ + y_ matches any of the following patterns, return True.'

a+b+c/.x_+y_:>u/;Print@FullForm[Plus[x,y]//HoldForm]

HoldForm[Plus[a,Plus[b,c]]]
HoldForm[Plus[b,Plus[a,c]]]
HoldForm[Plus[c,Plus[a,b]]]
HoldForm[Plus[Plus[a,b],c]]
HoldForm[Plus[Plus[a,c],b]]
HoldForm[Plus[Plus[b,c],a]]
HoldForm[Plus[a,b]]
HoldForm[Plus[b,a]]
HoldForm[Plus[a,c]]
HoldForm[Plus[c,a]]
HoldForm[Plus[b,c]]
HoldForm[Plus[c,b]]

a+b+c

Here are related posts on Orderless and OneIdentity, and this post shows how to reveal all built-in functions with Attributes categorize by their Attribute.

This is an excellent out-of-print book but there is plenty to learn from it. I'd compare it to David Wagner's Power Programming in Mathematica in its insight to how the Wolfram Language works.

Bahder, Thomas B. Mathematica for Scientists and Engineers. Reading, MA: Addison-Wesley. 1994.

No comments:

Post a Comment