Book Image

Haskell Design Patterns

By : Tikhon Jelvis, Ryan Lemmer
Book Image

Haskell Design Patterns

By: Tikhon Jelvis, Ryan Lemmer

Overview of this book

Design patterns and idioms can widen our perspective by showing us where to look, what to look at, and ultimately how to see what we are looking at. At their best, patterns are a shorthand method of communicating better ways to code (writing less, more maintainable, and more efficient code) This book starts with Haskell 98 and through the lens of patterns and idioms investigates the key advances and programming styles that together make "modern Haskell". Your journey begins with the three pillars of Haskell. Then you'll experience the problem with Lazy I/O, together with a solution. You'll also trace the hierarchy formed by Functor, Applicative, Arrow, and Monad. Next you'll explore how Fold and Map are generalized by Foldable and Traversable, which in turn is unified in a broader context by functional Lenses. You'll delve more deeply into the Type system, which will prepare you for an overview of Generic programming. In conclusion you go to the edge of Haskell by investigating the Kind system and how this relates to Dependently-typed programming
Table of Contents (14 chapters)

Monad


The Monad type-class inherits from Applicative (from GHC 7.10 onward; see the Monad as applicative section for more on this):

class (Applicative m) => Monad m where
  return :: a -> m a
  (>>=) :: m a -> (a -> m b) -> m b

The return function looks just like the pure function of the Applicative type-class (it lifts a value to Monad).

The bind operator (>>=) combines a Monad (m a) with a function (a -> m b), which we'll call a monadic function. The monadic function acts on type a of the first monad and returns a new monad of type (m b).

Let's make our Maybe' type a Monad:

import Control.Monad
import Control.Applicative

data Maybe' a = Just' a | Nothing'
  deriving (Show)

instance Functor Maybe' where
–- ...

instance Applicative Maybe' where
–- ...

instance Monad Maybe' where
  return x = Just' x
  Nothing'  >>= _   = Nothing'
  (Just' x) >>= f   = (f x)

The bind operator for Maybe' says:

  • Given Nothing', ignore the monadic function and simply return...