###### Finding Success (and Failure) in Haskell

This book is 90% complete

Last updated on 2019-04-02

# About the Book

Julie originally planned this course and taught a version of it at the Austin Haskell Meetup. The group had, by then, learned about monads and applicatives and how typeclasses work and all that good stuff, but it wasn't yet clear and concrete to them. It's one thing to talk about an idea and another to make use of it, so this series of lessons was planned to understand some things about monads and applicatives *by using them*. We started with a basic problem to solve – validating some user inputs – wrote a few basic functions and, over the course of a few hours, refactored it to use different types. Some of those types are monads, and some are not, and we were able to reach a concrete understanding of why and why not.

We've since revised and refined the course and edited the code to illustrate several additional core Haskell concepts while still being able to introduce them one at a time, to keep things tractable. By starting with basic language concepts (if-then-else and case) and growing a single example gradually, we made a book that is accessible to beginners, practical, and helpful to anyone who wants to get started writing programs in Haskell.

This book is for people who have just started getting into Haskell but would like to move quickly and understand by doing. We assume very little prior knowledge of Haskell. We work through examples without understanding theory or how and why things work too deeply. We give *just enough information*, just at the time when you need it.

**Motivation**

Most programming languages have, in some form or other, a way of dealing with failure -- or more specifically, a way to combine multiple smaller programs that might fail into a larger program that might fail. In an imperative style, this happens by executing the program's instructions in sequence and halting when an error occurs. Since the instruction failed to produce its value or effect, which was presumably necessary for the rest of the program, execution can continue no further, and whatever error information was produced by the failed subprogram constitutes the result of the program overall.

The deficiency of the process described above is that it doesn't always provide us with as much information as we might like when failure occurs. Because execution halts immediately, this approach can only ever give us information about the *first* problem that was encountered. Careless application of this error handling mechanism can give rise to unfortunate software behavior. Consider situations in which a user must fill out a form that will be checked programmatically for mistakes. An ideal program might show the user a list of *every* problem on the form; a flawed program may show only the first.

This is the problem that motivates this book. It is one that many programmers have encountered and, to our knowledge, one to which only functional programming with typeclasses permits a straightforward general solution in which writing the ideal program is no more difficult than writing the flawed one.

Programmers ask *Why monads*? This is why: The monad class is our tool for generalizing the notion of "program" beyond "run a series of subprograms until one fails." There is a whole world of other kinds of programs; in this book, we are concerned with programs for which the execution model is "run *all* of the subprograms, and if any of them fail, produce a list of all of the failures." Once we understand how the Monad and Applicative classes generalize programs, the solution to our problem falls almost effortlessly into our lap.

The book begins with two chapters on case expressions to ensure a solid foundation. From there, we write three functions for checking that inputs are valid passwords according to the rules of our system. The rest of the book iteratively expands on and refactors those functions into a small program that validates usernames and passwords, constructs a User (the product of a username and a password) if both are valid inputs, and returns pretty error messages if they are not. Along the way we learn about Monad and Applicative, how they are similar, how they differ, and how to use types to rethink our solutions to problems.

**Follow along**

We encourage you to follow along with the steps that we take in this book, type all of the code yourself, play with it in the Haskell REPL (GHCi), and do the exercises at the end of each chapter. You will learn to build a Haskell project with an executable. The only thing you'll need to install is Stack (and Stack will take care of installing the Haskell compiler, GHC, automatically). If you're already comfortable building a project by other means, such as with cabal-install or Nix, then you can still follow along, although we'll assume that you are able to adapt the instructions for your build system of choice.

There are exercises at the end of each chapter. Some are fairly straightforward extensions of what we've just done in the chapter, while others introduce new concepts. In general, they are ordered by difficulty, with the first exercises in the chapter being the most familiar and the last one most likely being the most challenging, probably introducing a new concept or giving you the least amount of help. A few stretch way beyond the current text to introduce entirely new libraries to encourage you to get closer to idiomatic Haskell. You should be able to adequately follow the main body of the text, however, without doing those exercises, so do not feel obligated to complete them all before moving on to the next chapter.

#### Table of Contents

**1 - Introduction to case expressions**

- Conditionals
- Reading type signatures
- Branching patterns
- Case expressions
- Sum types
- Exercises

**2 - Case expressions practice**

- The anagram checker
- The word validator
- Validate first, then compare
- Interactive program
- Exercises

**3 - Validation functions**

- Project setup
- checkPasswordLength
- requireAlphaNum
- cleanWhitespace
- Exercises

**4 - The Maybe Monad**

- Combining the validation functions
- De-nesting with infix operators
- Enter the monad
- TypeApplications
- Cases and binds
- Exercises

**5 - Refactoring with Either**

- Adding error messages
- Introducing Either
- The Either Monad
- Using Either
- Exercises

**6 - Working with newtypes**

- Introducing newtypes
- Declaring new types
- Using our new types
- Revising main
- Exercises
- Notes on monadic style

**7 - Introducing Applicative**

- Validating usernames
- Adding to main
- Constructing a User
- Constructors are functions
- Using Applicative
- Exercises

**8 - Refactoring with Validation**

- Introducing validation
- Adding a dependency
- Nominal refactoring
- Interpreting the errors
- An Error semigroup
- Using Applicative
- Exercises

**9 - Better Error Messages**

- The problem
- The error functions
- Gathering up the errors
- Lists upon lists
- Coercion
- Handling success
- The final main
- Exercises

**10 - Coercible**

- Enter Coercible
- What can be coerced?
- Updating the display function
- Type applications
- Coercibility is transitive
- Coercion via type parameters
- Coercing functions

**11 - Optics**

- (In progress)

**API reference**

- Maybe
- Either
- Validation
- List
- NonEmpty
- IO
- Text
- Functor
- Applicative
- Monad
- Semigroup
- Show
- Coercible

**Solutions to exercises**

### The Leanpub 45-day 100% Happiness Guarantee

Within **45 days of purchase** you can get a **100% refund** on any Leanpub purchase, in **two clicks**.

See full terms...