My question is, how does Haskell figure out that adding by type Integer — a Haskell query for type testTree gives Tree [Integer] —can be considered a monoid operation (if my terminology is correct)?
Can not! In fact, there is no Monoid instance for Integer .
Now, don't get me wrong - integers are monoids when added. However, they are also monoids under multiplication, and Haskell has no way of knowing what to use, therefore, newtype wrappers.
But ... none of this happens here. Moving on ...
(My own attempt to answer: the author a few paragraphs before this section describes how the Num type can be interpreted as a monoid type in two different ways: by transferring them to the Sum and Product type using (+) and (*) as functions mappend and 0 and 1 as a mempty element, respectively. Is the type “a” in (Tree a) somehow deduced as belonging to the type Sum (since Haskell interprets numerical values differently according to context) or is it completely different?]
Not a bad guess, but such a conclusion (finding an instance using Sum based on the arguments you gave) is beyond what Haskell can do for you.
There are two key points here - first of all, the Monoid restriction Monoid used only for certain functions, and not for folding in general. In particular, foldl does not actually need a Monoid instance Monoid all, because you provide a binary operation and an initial value to use it.
The second point is what I suspect you really need - how does it create a generic foldl that doesn't need Monoid , when all you define is foldMap , what does it do? To answer this, we can just look at the default implementation of foldl :
foldl :: (a -> b -> a) -> a -> tb -> a foldl fzt = appEndo (getDual (foldMap (Dual . Endo . flip f) t)) z
Here Endo is another newtype wrapper , especially for functions a -> a giving Monoid compositions with id as an identity, and Dual is a wrapper that changes the direction of Monoid . So he actually uses Monoid here, so he can glue using (+) along with the composition of the function, and then apply the result to the initial value.