Lesson 17. Design by composition—Semigroups and Monoids

 

After reading lesson 17, you’ll be able to

  • Create new functions with function composition
  • Use Semigroup to mix colors
  • Learn how to use guards in code
  • Solve probability problems with Monoid

In the preceding lesson, you looked at how sum types allow you to think outside the typical hierarchical design patterns present in most programming languages. Another important way that Haskell diverges from traditional software design is with the idea of composability. Composability means that you create something new by combining two like things.

What does it mean to combine two things? Here are some examples: you can concatenate two lists and get a new list, you can combine two documents and get a new document, and you can mix two colors and get a new color. In many programming languages, each of these methods of combining types would have its own unique operator or function. In much the same way that nearly every programming language offers a standard way to convert a type to a string, Haskell offers a standard way to combine instances of the same type together.

Consider this

So far, when you’ve combined multiple strings, you’ve used ++. This can get tedious for larger strings:

"this" ++ " " ++ "is" ++ " " ++ "a" ++ " " ++ "bit" ++ " " ++ "much"

Is there a better way to solve this?

17.1. Intro to composability—combining functions

17.2. Combining like types: Semigroups

17.3. Composing with identity: Monoids

Summary