Finding Success (and Failure) in Haskell
Finding Success (and Failure) in Haskell
Fall in love with applicative functors
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.
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.
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.
- 1 - Introduction to case expressions
- Reading type signatures
- Branching patterns
- Case expressions
- Sum types
- 2 - Case expressions practice
- The anagram checker
- The word validator
- Validate first, then compare
- Interactive program
- 3 - Validation functions
- Project setup
- 4 - The Maybe Monad
- Combining the validation functions
- De-nesting with infix operators
- Enter the monad
- Cases and binds
- 5 - Refactoring with Either
- Adding error messages
- Introducing Either
- The Either Monad
- Using Either
- 6 - Working with newtypes
- Introducing newtypes
- Declaring new types
- Using our new types
- Revising main
- Notes on monadic style
- 7 - Introducing Applicative
- Validating usernames
- Adding to main
- Constructing a User
- Constructors are functions
- Using Applicative
- 8 - Refactoring with Validation
- Introducing validation
- Adding a dependency
- Nominal refactoring
- Interpreting the errors
- An Error semigroup
- Using Applicative
- 9 - Better Error Messages
- The problem
- The error functions
- Gathering up the errors
- Lists upon lists
- Handling success
- The final main
- 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
- Solutions to exercises
- API reference
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
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.
C++ Best PracticesJason Turner
Level up your C++, get the tools working for you, eliminate common problems, and move on to more exciting things!
OpenIntro StatisticsDavid Diez, Christopher Barr, Mine Cetinkaya-Rundel, and OpenIntro
A 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.
Functional Design and ArchitectureAlexander Granin
Software Design in Functional Programming, Design Patterns and Practices, Methodologies and Application Architectures. How to build real software in Haskell with less efforts and low risks. The first complete source of knowledge.
Atomic KotlinBruce Eckel and Svetlana Isakova
For both beginning and experienced programmers! From the author of the multi-award-winning Thinking in C++ and Thinking in Java together with a member of the Kotlin language team comes a book that breaks the concepts into small, easy-to-digest "atoms," along with exercises supported by hints and solutions directly inside IntelliJ IDEA!
C++20 is the next big C++ standard after C++11. As C++11 did it, C++20 changes the way we program modern C++. This change is, in particular, due to the big four of C++20: ranges, coroutines, concepts, and modules.
The book is almost daily updated. These incremental updates ease my interaction with the proofreaders.
Introductory Statistics with Randomization and SimulationMine Cetinkaya-Rundel, Christopher Barr, OpenIntro, and David Diez
A complete foundation for Statistics, also serving as a foundation for Data Science, that introduces inference using randomization and simulation while covering traditional methods.
Leanpub revenue supports OpenIntro, so we can provide free desk copies to teachers interested in using our books in the classroom.
More resources: openintro.org.
Java OOP Done RightAlan Mellor
Object Oriented Programming is still a great way to create clean, maintainable code. But only if you use it right.
This book gives you 25 years of OO best practice, ready to use.
You'll learn to design objects behaviour-first, use TDD to help, then confidently apply Design Patterns, SOLID principles and Refactoring to make clean, crafted code.
Ansible for DevOpsJeff Geerling
Ansible is a simple, but powerful, server and configuration management tool. Learn to use Ansible effectively, whether you manage one server—or thousands.
Composing SoftwareEric Elliott
All software design is composition: the act of breaking complex problems down into smaller problems and composing those solutions. Most developers have a limited understanding of compositional techniques. It's time for that to change.
Cloud StrategyGregor Hohpe
“Strategy is the difference between making a wish and making it come true.” A successful migration to the cloud shouldn’t be driven by wishes, but guided by a sound strategy, frameworks, and decision models. This book tells you how—without becoming superficial nor getting lost in technology and product details.
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...
CCIE Service Provider Ultimate Study Bundle
2 BooksPiotr 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...
Cisco CCNA 200-301 Complet
4 BooksCe lot comprend les quatre volumes du guide préparation à l'examen de certification Cisco CCNA 200-301.
CCDE Practical Studies (All labs)
3 BooksCCDE lab
Modern Management Made Easy
3 BooksRead all three Modern Management Made Easy books. Learn to manage yourself, lead and serve others, and lead the organization.
The Future of Digital Health
6 BooksWe 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 and how technology giants such as Amazon or Google want to conquer...
Modern C++ by Nicolai Josuttis
Django for Beginners/APIs/Professionals
"The C++ Standard Library" and "Concurrency with Modern C++"
2 BooksGet my books "The C++ Standard Library" and "Concurrency with Modern C++" in a bundle. The first book gives you the details you should know about the C++ standard library; the second one dives deeper into concurrency with modern C++. In sum, you get more than 600 pages full of modern C++ and about 250 source files presenting the standard library...
Linux Administration Complet
4 BooksCe 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é...