Transforming All, Any, Max, & Min from Semigroups to Monoids

Thomas Greco
InstructorThomas Greco
Share this video with your friends

Social Share Links

Send Tweet

This lesson shows viewers how to transform the following semigroups to be valid monoid instances: All, Any, Max, Min.

Thomas Greco: [0:00] Although semigroups are powerful, they're not nearly as powerful as the monoids, because they can't have no empty values. Luckily, we can upgrade semigroups to monoids with ease.

[0:15] All we need to do is define an identity function which is going to come in the form of empty. To kick things off, we're going to define an empty in our Any semigroup, and this is going to be an Any of false.

[0:36] Now that we have that done, let's move on to All. Whereas empty only needs one of the values that it's concatenating with to be truthy, All looks for truthiness in all of them. As a result of that, it has true as its identity. Now, we have these. Let's just test them out real quick and we'll say All.empty().concat(All(true).concat(All(true))).

[1:29] Then below this, we'll do the same with Any. All right. Now, if we run these, boom. We see that we get true for both which should make sense granted that we know the laws, and if we decided to just concat the empty on the end. Now, we still get the correct behavior.

[2:32] Moving forward, let's upgrade our Max and Min semigroups. These identities are also going to be very similar. When defining the empty on Max, we're going to return a Max of -Infinity. On the other hand, Min is going to return a Min of Infinity or positive Infinity.

[3:22] The fact that Max has a negative number as its identity and Min has a positive might seem a bit confusing. However, if we just think about it, Max is always trying to get the larger of two values and by having an idea of -Infinity, this ensures that it will always be able to pull out a larger number.

[3:50] Min, on the other hand, has positive Infinity, because it's always looking for the lower number. Therefore, comparing any number to its identity of Infinity is always going to return the number being compared.

[4:10] Just to test this out, we're going to add this log statement below. Then again, I'm going to start with our empty, and then concat a bunch of Mins. Now, I did the exact same thing with Max.

[4:42] Boom, we see that we're getting a Min of 5 and a Max of 10. Again, we'll see that everything still works just as planned when we concat these empties onto the end. Now, Min is the same, however Max has a larger value now as we've passed an 11.