Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Haskell Design Patterns
  • Toc
  • feedback
Haskell Design Patterns

Haskell Design Patterns

By : Lemmer
4.1 (9)
close
Haskell Design Patterns

Haskell Design Patterns

4.1 (9)
By: 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 (9 chapters)
close

Monads

The monad typeclass is best understood by looking at from many perspectives. That is why this book has no definitive section or chapter on monad. Instead, we will successively peel of the layers of this abstraction and make good use of it.

Let's begin by looking at a simple example of interpreting expressions:

data Expr = Lit Int | Div Expr Expr

eval :: Expr -> Int
eval (Lit a) = a
eval (Div a b) = eval a `div` eval b

The eval function interprets expressions written in our Expr data type:

(eval (Lit 42))      –- 42
(eval (Div (Lit 44) (Lit 11)))  -- 4

Stripped of real-world concerns, this is very elegant. Now let's add (naive) capability to deal with errors in our interpreter. Instead of the eval function returning integers, we'll return a Try data type, which caters for success (Return) and failure (Error):

data Try a = Err String | Return a

The refactored evalTry function is now much more syntactically noisy with case statements:

evalTry :: Expr -> Try Int
evalTry (Lit a) = Return a
evalTry (Div a b) = case (evalTry a) of
      Err e     -> Err e
      Return a' -> case (evalTry b) of
         Err e  -> Err e
         Return b' -> divTry a' b'

-- helper function
divTry :: Int -> Int -> Try Int
divTry a b = if b == 0
    then Err "Div by Zero"
    else Return (a `div` b)

The reason for the noise is that we have to explicitly propagate errors. If (evalTry a) fails, we return Err and bypass evaluation of the second argument.

We've used the Try data type to make failure more explicit, but it has come at a cost. This is precisely where monads come into play. Let's make our Try data type a monad:

instance Monad Try where
  return x   = Return x
  fail msg   = Err msg

  Err e    >>= _   = Err e
  Return a >>= f   = f a

Next, we refactor evalTry by using the bind operator (>>=):

evalTry' :: Expr -> Try Int
evalTry' (Lit a)   = Return a
evalTry' (Div a b) = (evalTry' a) >>= \a' ->
                       (evalTry' b) >>= \b' ->
                         divTry a' b'

-– evalTry' (Div (Lit 44) (Lit 0))

The bind operator enables error propagation:

Err e  >>= _   = Err e

Whenever we have an Err function, the subsequent part of the bind chain will be ignored and will thereby propagate the error. While this gets rid of our case statements, it is hardly very friendly. Let's rewrite it using the do notation:

evalTry'' (Lit a) = Return a
evalTry'' (Div a b)
  = do
     a' <- (evalTry' a)
     b' <- (evalTry' b)
     divTry a' b'

The Try data type helped us make failure more explicit, while making it a monad made it easier to work with. In this same way, monads can be used to make many other "effects" more explicit.

 

"Being explicit about effects is extremely useful, and this is something that we believe may ultimately be seen as one of Haskell's main impacts on mainstream programming"

 
 --History of Haskell, Hudak et al.

The IO monad is particularly interesting and played an important role in the development of Haskell. When Haskell was first conceived, there were no monads and also no clear solution to the "problem of side effects". In 1989, Eugenio Moggi used monads, from Category theory, to describe programming language features. Phillip Wadler, a then member of the Haskell Committee, recognized that it was possible to express Moggi's ideas in Haskell code:

 

"Although Wadler's development of Moggi's ideas was not directed towards the question of input/output, he and others at Glasgow soon realised that monads provided an ideal framework for I/O"

 
 --History of Haskell, Hudak et al

Because Haskell is purely functional, side effects call for special treatment. We will devote a whole chapter to exploring this topic in Chapter 2, Patterns for I/O.

Composing monads and structuring programs

As useful as monads are for capturing effects, we also need to compose them, for example, how do we use monads for failure, I/O, and logging together?

In the same way that functional composition allows us to write more focused functions that can be combined together, monad composition allows us to create more focused monads, to be recombined in different ways. In Chapter 3: Patterns for Composition, we will explore monad transformers and how to create "monad stacks" of transformers to achieve monad composition.

bookmark search playlist font-size

Change the font size

margin-width

Change margin width

day-mode

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Delete Bookmark

Modal Close icon
Are you sure you want to delete it?
Cancel
Yes, Delete