12 Applicative and traversable functors

 

This chapter covers:

  • Defining the applicative functor algebraic structure
  • Grasping the relationship, differences and tradeoffs between applicatives and monads
  • Proving applicative laws of identity, associativity and naturality
  • Defining the traversable functor and its uses
  • Combining, fusing and nesting traversable structures
  • Monad composition using the monad transformer

In the previous chapter on monads, we saw how a lot of the functions we’ve been writing for different data types and combinator libraries can be expressed in terms of a single interface, Monad. Monads provide powerful functionality as we’ve seen by the fact that we can use flatMap to write what seems like an imperative program in a purely functional way.

In this chapter, we’ll learn about a related abstraction, the applicative functor, which is less powerful than the monad, but more general (and hence more common). The process of arriving at applicative functors will also provide some insight into discovering such abstractions, and we’ll use some of these ideas to uncover another useful abstraction, the traversable functor. It may take some time for the full significance and usefulness of these abstractions to sink in, but you’ll see them popping up again and again in your daily work with FP if you pay attention.

12.1 Generalizing monads for reusability

12.2 Applicatives as alternative abstraction to monad

12.3 The difference between monads and applicative functors

12.3.1 The Option applicative versus the Option monad

12.3.2 The Parser applicative versus the Parser monad

12.4 The advantages of applicative functors

12.4.1 Not all applicative functors are monads

12.5 Reasoning about programs through the applicative laws

12.5.1 Laws of left and right identity

12.5.2 Law of associativity

12.5.3 Law of naturality

12.6 Abstracting traverse and sequence using traversable functors

12.7 Using Traversable to iteratively transform higher kinds

12.7.1 From monoids to applicative functors

12.7.2 Traversing collections while propagating state actions

12.7.3 Combining traversable structures

12.7.4 Traversal fusion for single pass efficiency

12.8 Summary