Lesson 28. A peek at the Applicative type class: using functions in a context

 

After reading lesson 28, you’ll be able to

  • Build an application that handles missing data
  • Extend the power of the Functor type class with the Applicative type
  • Use Applicative to use one data model in many contexts

In the preceding lesson, you learned how the Functor type class allows you to perform computation inside a container such as List or a context such as Maybe and IO. The key method behind Functor is fmap (more commonly, the <$> operator), which works just like map on a list. In this lesson, you’ll work with a more powerful type class called Applicative. The Applicative type class extends the power of Functor by allowing you to use functions that are themselves in a context.

Although this may not seem useful, it allows you to chain together long sequences of computation in a context such as IO or Maybe.

In your first example, you’ll see the limitations of Functor by building a command-line tool that allows the user to calculate the distance between two cities. The issue is that you need to pass two Maybe values to a function, which surprisingly Functor can’t do. You’ll then see how Applicative resolves this issue. After you learn about Applicative, you’ll see how this can help you create data in the context of either IO or Maybe, while allowing you to reuse the majority of your code.

28.1. A command-line application for calculating the distance between cities

28.2. Using <*> for partial application in a context

28.3. Using <*> to create data in a context

Summary