Finding Success (and Failure) in Haskell
$25.00
Minimum price
$35.00
Suggested price

Finding Success (and Failure) in Haskell

Fall in love with applicative functors

About the Book

Also available in paperback from Lulu

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, 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; learn about Stack and how to install it at https://haskellstack.org. 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.

GHC comes with a REPL ("read-evaluate-print loop") called GHCi ("GHC interactive") which makes it easy to run quick experiments to try things out.

Each chapter except one ends with exercises. 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.

About the Author

Type Classes
Type Classes

Type Classes is Chris Martin and Julie Moronuki. We've been writing about Haskell together since 2018.

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 - Generalizing further
    • Designing a typeclass
    • Folding over sum types
    • Desire for a generalized fmap
    • The lens library
    • The Success and Failure prisms
    • The Either-Validation isomorphism
    • The Validate class
    • Exercises
  • Solutions to exercises
  • API reference
    • Bool
    • Maybe
    • Either
    • Validation
    • List
    • NonEmpty
    • IO
    • Text
    • Functor
    • Applicative
    • Monad
    • Semigroup
    • Show
    • Coercible
    • Prism
    • Lens
    • Iso
    • Validate

Other books by this author

The Leanpub 60 Day 100% Happiness Guarantee

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

Now, this is technically risky for us, since you'll have the book or course files either way. But we're so confident in our products and services, and in our authors and readers, that we're happy to offer a full money back guarantee for everything we sell.

You can only find out how good something is by trying it, and because of our 100% money back guarantee there's literally no risk to do so!

So, there's no reason not to click the Add to Cart button, is there?

See full terms...

80% Royalties. Earn $16 on a $20 book.

We pay 80% royalties. That's not a typo: you earn $16 on a $20 sale. If we sell 5000 non-refunded copies of your book or course for $20, you'll earn $80,000.

(Yes, some authors have already earned much more than that on Leanpub.)

In fact, authors have earnedover $13 millionwriting, publishing and selling on Leanpub.

Learn more about writing on Leanpub

Free Updates. DRM Free.

If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).

Most Leanpub books are available in PDF (for computers) and EPUB (for phones, tablets and Kindle). The formats that a book includes are shown at the top right corner of this page.

Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.

Learn more about Leanpub's ebook formats and where to read them

Write and Publish on Leanpub

You can use Leanpub to easily write, publish and sell in-progress and completed ebooks and online courses!

Leanpub is a powerful platform for serious authors, combining a simple, elegant writing and publishing workflow with a store focused on selling in-progress ebooks.

Leanpub is a magical typewriter for authors: just write in plain text, and to publish your ebook, just click a button. (Or, if you are producing your ebook your own way, you can even upload your own PDF and/or EPUB files and then publish with one click!) It really is that easy.

Learn more about writing on Leanpub