Finding Success (and Failure) in Haskell
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.
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.
See full terms
Do Well. Do Good.
Authors have earned$11,586,736writing, publishing and selling on Leanpub, earning 80% royalties while saving up to 25 million pounds of CO2 and up to 46,000 trees.
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), EPUB (for phones and tablets) and MOBI (for 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
Top Books
SignalR on .NET 6 - the Complete Guide
Fiodar SazanavetsLearn everything there is to learn about SignalR and how to integrate it with the latest .NET 6 and C# 10 features. Learn how to connect any type of client to SignalR, including plain WebSocket client. Learn how to build interactive applications that can communicate with each other in real time without making excessive calls.
The easiest way to learn design patterns
Fiodar SazanavetsLearn design patterns in the easiest way possible. You will no longer have to brute-force your way through each one of them while trying to figure out how it works. The book provides a unique methodology that will make your understanding of design patterns stick. It can also be used as a reference book where you can find design patterns in seconds.
Jetpack Compose internals
Jorge CastilloJetpack Compose is the future of Android UI. Master how it works internally and become a more efficient developer with it. You'll also find it valuable if you are not an Android dev. This book provides all the details to understand how the Compose compiler & runtime work, and how to create a client library using them.
Functional event-driven architecture: Powered by Scala 3
Gabriel VolpeExplore the event-driven architecture (EDA) in a purely functional way, mainly powered by Fs2 streams in Scala 3!
Leverage your functional programming skills by designing and writing stateless microservices that scale, powered by stateful message brokers.
Tech Giants in Healthcare
Dr. Bertalan MeskoThis comprehensive guide, Tech Giants in Healthcare, clarifies how and why big tech companies step into healthcare, and breaks it down from one market player to the other in what direction they are going, what tools they are using and what horizons they have in front of them.
OpenIntro Statistics
David Diez, Christopher Barr, Mine Cetinkaya-Rundel, and OpenIntroA complete foundation for Statistics, also serving as a foundation for Data Science.
Leanpub revenue supports OpenIntro (US-based nonprofit) so we can provide free desk copies to teachers interested in using OpenIntro Statistics in the classroom and expand the project to support free textbooks in other subjects.
More resources: openintro.org.
Ansible for DevOps
Jeff GeerlingAnsible is a simple, but powerful, server and configuration management tool. Learn to use Ansible effectively, whether you manage one server—or thousands.
C++20 - The Complete Guide
Nicolai M. JosuttisAll the new language and library features of C++20 (for those who know previous versions).
The book presents all new language and library features of C++20. Learn how this impacts day-to-day programming, to benefit in practice, to combine new features, and to avoid all new traps.
Buy early, pay less, free updates.
Other books:
CCIE Service Provider Version 4 Written and Lab Exam Comprehensive Guide
Nicholas RussoThe service provider landscape has changed rapidly over the past several years. Networking vendors are continuing to propose new standards, techniques, and procedures for overcoming new challenges while concurrently reducing costs and delivering new services. Cisco has recently updated the CCIE Service Provider track to reflect these changes; this book represents the author's personal journey in achieving that certification.
R Programming for Data Science
Roger D. PengThis book brings the fundamentals of R programming to you, using the same material developed as part of the industry-leading Johns Hopkins Data Science Specialization. The skills taught in this book will lay the foundation for you to begin your journey learning data science. Printed copies of this book are available through Lulu.
Top Bundles
- #1
All the Books of The Medical Futurist
6 Books
We put together the most popular books from The Medical Futurist to provide a clear picture about the major trends shaping the future of medicine and healthcare. Digital health technologies, artificial intelligence, the future of 20 medical specialties, big pharma, data privacy, digital health investments and how technology giants such as Amazon... - #2
Practical FP in Scala + Functional event-driven architecture
2 Books
Practical FP in Scala (A hands-on approach) & Functional event-driven architecture, aka FEDA, (Powered by Scala 3), together as a bundle! The content of PFP in Scala is a requirement to understand FEDA so why not take advantage of this bundle!? - #3
Software Architecture for Developers: Volumes 1 & 2 - Technical leadership and communication
2 Books
"Software Architecture for Developers" is a practical and pragmatic guide to modern, lightweight software architecture, specifically aimed at developers. You'll learn:The essence of software architecture.Why the software architecture role should include coding, coaching and collaboration.The things that you really need to think about before... - #4
CCIE Service Provider Ultimate Study Bundle
2 Books
Piotr Jablonski, Lukasz Bromirski, and Nick Russo have joined forces to deliver the only CCIE Service Provider training resource you'll ever need. This bundle contains a detailed and challenging collection of workbook labs, plus an extensively detailed technical reference guide. All of us have earned the CCIE Service Provider certification... - #6
Pattern-Oriented Memory Forensics and Malware Detection
2 Books
This training bundle for security engineers and researchers, malware and memory forensics analysts includes two accelerated training courses for Windows memory dump analysis using WinDbg. It is also useful for technical support and escalation engineers who analyze memory dumps from complex software environments and need to check for possible... - #7
Modern C++ Collection
3 Books
Get All about Modern C++C++ Standard Library, including C++20Concurrency with Modern C++, including C++20C++20Each book has about 200 complete code examples. Updates are included. When I update one of the books, you immediately get the updated bundle. You can expect significant updates to each new C++ standard (C++23, C++26, .. ) and also... - #8
Linux Administration Complet
4 Books
Ce lot comprend les quatre volumes du Guide Linux Administration :Linux Administration, Volume 1, Administration fondamentale : Guide pratique de préparation aux examens de certification LPIC 1, Linux Essentials, RHCSA et LFCS. Administration fondamentale. Introduction à Linux. Le Shell. Traitement du texte. Arborescence de fichiers. Sécurité... - #10
Growing Agile: The Complete Coach's Guide
7 Books
Growing Agile: Coach's Guide Series This bundle provides a collection of training and workshop plans for a variety of agile topics. The series is aimed at agile coaches, trainers and ScrumMasters who often find themselves needing to help teams understand agile concepts. Each book in the series provides the plans, slides, handouts and activity...