Working with Monoid
Monoid is an important and very useful type class. A Monoid assumes two behaviors:
- There is a default or empty value of the data type.
- Given two values of the data type, they can be combined to create a single value.
The simplest example of a Monoid is Integer
. We can define an empty value of an Integer
as 0
. We can then use addition
as an operation to combine two Integers
. In this recipe, we will define a data type Option
and define an instance for Monoid.
Getting ready
Create a new project called working-with-monoid
with the simple
template using Stack:
stack new working-with-monoid simple
Change into the newly created project directory.
How to do it...
- Start editing
src/Main.hs
. Addimport Data.Monoid
at the top. This module contains the definition of theMonoid
type class. - Define a data type
Option
. The data contains a Boolean field and a list ofString
:
data Option = Option { boolOption :: Bool, selections :: [String] } deriving Show
- Define...