Creating Semigroup Data Types from Scratch

Thomas Greco
InstructorThomas Greco
Share this video with your friends

Social Share Links

Send Tweet

Semi-groups are an important part of functional programming. They're not quite monoids, however, they provide us with the foundation we need to create monoids.

In this video, we'll learn about semigroups and see how they provide us with a generic interface for combining values using a .concat method. By the end of the lesson, you will have learned about the properties that a type must possess in order to be considered a valid semigroup.

Fantasyland Docs - Semigroup

Thomas Greco: [0:00] Semi-groups provide us with an interface for combining one or more values together. Here, I'm just creating a semi-group called Sum. The first thing we'll do is just set the value being passed in. The next thing we need to do is add a concat function. All semi-groups need to have this concat function.

[0:31] What this is going to do is it's going to take in another semi-group and in this instance, it's going to use addition to combine both these values. Keep in mind that we're wrapping this return value in the Sum, as this will allow us to continue concatenating values for as long as we need.

[0:54] [inaudible] console.log statement, and if we have a Sum(10) and we concatenate that with the Sum(20), we should see that we get 30 as our result. If I just execute this code...Remove these statements. If I execute it, I see that we get that value of 30 inside of our object.