0

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?

fragant
  • 361
  • 4
  • 16
  • 2
    "fold" isn't a datatype, is it, so it can't be a monoid... Did you mean why numbers aren't monoids? – mniip Jul 12 '15 at 15:19
  • I meant fold can bee applied on structures which can build monoids or even not – fragant Jul 12 '15 at 15:27
  • Then are you asking if list is a monoid? Yes it is. – mniip Jul 12 '15 at 15:28
  • The definition of my lecture says: A quantity M with a binary operation (o) :: M x M -> M is called monoid if the operation (o) is associative and there is a neutral element e. So the example for a structure which doesn't build a monoid is the foldr applied to `(\_ n -> 1+n) 0` which is the definition of the length function. But why is this especially an example for the opposite of the definition? I fullfills it – fragant Jul 12 '15 at 15:44
  • 1
    @fragant "foldr applied to (\\_ n -> 1+n) 0" has type `[a] -> Integer`, it is indeed not a monoid. – mniip Jul 12 '15 at 16:36

1 Answers1

3

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.

Ørjan Johansen
  • 18,119
  • 3
  • 43
  • 53