Lesson 31. Making Monads easier with do-notation

 

After reading lesson 31, you’ll be able to

  • Use do-notation to simplify working with Monads
  • Translate from Monad methods and lambdas to do-notation
  • Generate code from one instance of Monad to all Monads

The Monad type class allows for powerful abstraction when using types in context. But the use of the Monad methods >>=, >>, and return quickly becomes cumbersome. In this lesson, you’ll look at two useful tools that make working with Monads significantly easier. The first is do-notation, which you already made heavy use of in unit 4. Now you’ll get a sense of how do-notation works behind the scenes. After this, you’ll learn about how List works as a Monad. This leads to another abstraction over Monads that makes them even easier to work with: list comprehensions. Although it’s important to understand the methods of the Monad type class, in practice most of the work you’ll do with Monads involves using these methods of simplifying your code.

In the preceding lesson, you left off with a helloName IO action that asks the user for their name and then says hello to them.

Listing 31.1. helloName

31.1. Do-notation revisited

31.2. Using do-notation to reuse the same code in different contexts

Summary