Book Image

Haskell Cookbook

Book Image

Haskell Cookbook

Overview of this book

Haskell is a purely functional language that has the great ability to develop large and difficult, but easily maintainable software. Haskell Cookbook provides recipes that start by illustrating the principles of functional programming in Haskell, and then gradually build up your expertise in creating industrial-strength programs to accomplish any goal. The book covers topics such as Functors, Applicatives, Monads, and Transformers. You will learn various ways to handle state in your application and explore advanced topics such as Generalized Algebraic Data Types, higher kind types, existential types, and type families. The book will discuss the association of lenses with type classes such as Functor, Foldable, and Traversable to help you manage deep data structures. With the help of the wide selection of examples in this book, you will be able to upgrade your Haskell programming skills and develop scalable software idiomatically.
Table of Contents (13 chapters)

Working with Monoid

Monoid is an important and very useful type class. A Monoid assumes two behaviors:

  1. There is a default or empty value of the data type.
  2. 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.

...