Basic Examples (2)
Expressions with the same LeafCount may have different total over their leaves:
Apply a function to each leaf before taking the total:
Scope (6)
Take the total over the leaves of a rational expression:
Sum over all leaves of an algebraic or complex expression:
Sum over non-integer leaves:
Sum over the leaves of any expression:
Apply an arbitrary function to each leaf:
Apply a custom wrapping function other than Plus to each leaf and function-of-the-leaf:
Options (2)
Heads (2)
Through the option Heads set to False, only proper leaf nodes are counted (parent nodes count 0):
Another example with 4 discarded heads:
Check the FullForm:
Applications (3)
LeafTotal can be used as option value for ComplexityFunction to Simplify algebraic expressions:
Another example with Log:
Select the "simplest" element of a list according to a custom function applied to each leaf:
Certain functions like ResourceFunction["AlgebraicRange"] tend to overproduce complex closed forms:
LeafTotal[expr] allows to select only the simpler ones:
The resulting numeric distribution can still be nearly uniform:
Properties and Relations (4)
If all numeric leaves of an algebraic expression are equal to 1 or -1, LeafComplexity[expr] has the same value as LeafCount[expr]+1:
If no 0 appears in the expression, LeafComplexity[expr] is greater than LeafCount[expr]+1:
If 0s are present in the expression, LeafComplexity[expr] can be less than LeafCount[expr]+1:
If Infinity appears anywhere in the expression and does evaluate to 0, infinite is also the value of LeafComplexity:
LeafComplexity[expr] can be also computed in terms of Cases as follows:
Notice though this is more involved and less efficient than the actual recursive definition.
Neat Examples (2)
Define a general LeafComplexity with doubly nested Log and Exp:
Applying this to Range[n] for a few natural numbers n shows no Overflow and some interesting symbolic and numeric pattern: