Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Semigroup examples

    Brian LonsdorfBrian Lonsdorf

    A few examples of Semigroup definitions



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    Suppose we have a game and one of our players, Niko here, wants to merge their accounts. They've accidentally made two accounts. What we can do is think about how are we going to combine these two things? Whenever we think of combining we should be thinking semigroup, because that is a way to concat two things or combine two things together.

    Now, one of the properties we can exploit is if a data structure is entirely made up of semigroups it will be a semigroup itself. If I can concat all the pieces of my data structure then my data structure is therefore concatable.

    We want to concat these two objects together and what we can do here is say, instead of concating the name into a string, NikoNiko -- that would be kind of strange -- why don't we go ahead and change the semigroup to first, here around the name, so it knows how to combine it correctly?

    Then, with isPaid, I'd like to combine these two bullions. If they're both paid or if all of them are paid then we're paid. Let's do that. Let's say all. That will keep us in good standing. No cheating there. Points will be just the sum of the points.

    As it happens, these friends here are just an array so it will already be able to concat on that. It's a semigroup there. We can go ahead and write, "Constant results" is the account one concated with an account two here. This isn't going to quite work yet because objects do not have a concat method on them.

    What I'll do here is I brought in my own library of immutable extensions. It works like Immutable JS with some extra little flair on the end of it. This is your custom library, but I wouldn't necessarily call it custom.

    This is just a reimplementation of the same things you'll find in Scala or Haskell or what have you. They're just generic data structures. But anyway, where were we? Here we have a map, objects here, or a map type that will define concat exactly like we like it.

    Now we can inaudible that log our results and see that we've gone ahead and concated both together. Oh, we have to call 2 JS on this. It's Immutable JS, you have to do these things.

    There we go. Now you can see that the name has kept the first part. It is paid if all of it is paid. The sum of the points is there and all of our friends have been carried over.