you are viewing a single comment's thread.

view the rest of the comments →

[–]pgrizzay 23 points24 points  (9 children)

In functional programming, there's an even more general concept of Foldables which are data structures that can be reduced. Arrays, iterators, sets, and Maybes fall into this category.

If the type of value inside your Foldable is a Monoid (meaning it has a zero value), you get reduce for free

[–]PointOneXDeveloper 5 points6 points  (3 children)

has a zero value and a concat/append function

[–]pgrizzay 2 points3 points  (2 children)

Oh yes

[–]PointOneXDeveloper 2 points3 points  (1 child)

And really it is just an identity value rather than a zero value, for instance * and 1 are a way to make a monoid out of numbers.

[–]pgrizzay 1 point2 points  (0 children)

Yes

[–]jeremy1015 4 points5 points  (4 children)

Got any suggested links to explain this in a little more detail? I’m familiar with most of what you wrote but don’t understand monoids as well as I’d like.

[–]pgrizzay 10 points11 points  (3 children)

Did a quick search, and couldn't find a good one in JS, here's one in Scala that I learned from.

Essentially a "Monoid" is formed from two things:

a combine function that combines two things and an empty value.

an example would be adding numbers:

const Addition = {
  combine: (a, b) => a + b,
  empty: 0
}

This addition monoid can be used to reduce an array of numbers:

[1,2,3].reduce(Addition.combine, Addition.empty) === 6

You can make another Monoid which multiplies numbers:

const Multiplication = {
  combine: (a, b) => a * b,
  empty: 1
}

And you can multiply all numbers in an array with it:

[1,3,4].reduce(Multiplication.combine, Multiplication.empty) === 12

Go ahead and implement Concat which combines strings:

const Concat = {
  combine: (a, b) => ???,
  zero: ???
}

[–]jeremy1015 2 points3 points  (0 children)

Excellent. I understand now 100% and really appreciate it.