Search code examples
haskellfoldmonoids

Folds above functions - monoids


Why is the fold above the length of a list no monoid?

length = foldr (\_ n -> 1+n) 0

Isn't it associative and has the neutral element 0 so that it should be a monoid?


Solution

  • It is hard for me to understand what you're really asking, and I have a suspicion that the exact phrasing of the claim from your lecture might matter.

    But by the most intuitive interpretation I can think of you are right, as mathematically, the length function is a "monoid homomorphism", mapping the monoid of lists with the concatenation operation to the monoid of integers with the addition operation.

    It's technically not so in Haskell, but mostly for the reason that number types haven't been given a Monoid instance because there are two obvious operations to choose between, addition and multiplication. Another reason is that lists in Haskell can be infinite, so length doesn't always give a result.