[Haskell-cafe] A clarification about what happens under the hood with foldMap

Chaddaï Fouché chaddai.fouche at gmail.com
Tue Oct 23 10:16:38 CEST 2012

Le 23 oct. 2012 09:54, "Alfredo Di Napoli" <alfredo.dinapoli at gmail.com> a
écrit :
> What this code does is straighforward. I was struck from the following
sentences in LYAH:
>> Notice that we didn't have to provide the function that takes a value
and returns a monoid value.
>> We receive that function as a parameter to foldMap and all we have to
decide is where to apply
>> that function and how to join up the resulting monoids from it.
> This is obvious, so in case of (+) f = Sum, so f 3 = Sum 3 which is a
> What I was wondering about is how Haskell knows that it has to pass, for
example, Sum in case of (+) and Product in case of (*)?
> In other term, I'm missing the logical piece of the puzzle which maps the
associative binary function passed to fold up to our foldMap declaration.

Haskell doesn't know it has to pass anything ! As the doc said, this is a
parameter to foldmap : so you would use "treeSum = foldmap Sum" for
example. And the binary function associed would be determined by the monoid
instance. Here that would be (+) because that's what mappend is for Sum (or
rather for Sum Int).

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20121023/de316066/attachment.htm>

More information about the Haskell-Cafe mailing list