liveBook · Manning

Applicative functor

As explained in The Coder Cafe

An applicative is a functional abstraction that applies a function held in a context to a value held in a context, supporting the combination of independent contextual computations.

An applicative functor applies a function held in a context to a value held in the same kind of context. It is useful when wrapped computations can be combined independently, such as separate validations. section 3.2.2 section 3.4

A functor’s fmap handles an ordinary function and a wrapped value. If the function might itself be missing, it can be held in a Maybe; if there are several possible functions, they can be held in a list. In Haskell, <*> handles the case where both the function and value are wrapped. section 3.2.1 section 3.2.2

applicativeEx :: Maybe Int
applicativeEx = Just (+ 1) <*> Just 42 -- Result: Just 43

Here, Just (+ 1) <*> Just 42 produces Just 43: the function and value both remain in the Maybe context. section 3.2.2

The contexts must match: a Maybe-wrapped function cannot be applied with <*> to a list of values. With a list of functions and a list of values, each function is applied to each value. When the function is not wrapped, <$> provides the mapping form instead. section 3.2.2

Applicatives do not solve every sequencing problem. In a greeting example, greet <$> Just name <*> validateAge age fails to compile: greet takes only the name, so the first part has already produced a wrapped greeting rather than a function that can accept the age. When a later computation must depend on an earlier result, a monad is the next abstraction. section 3.2.4 section 3.2

How The Coder Cafe covers it

How deep it goes
Works through Maybe and list application, context matching, and a failing greeting attempt; stops short of formal laws.
Examples
Uses a Maybe-wrapped increment, lists of functions and values, and an age-validated greeting that fails to type-check.
What it assumes
Builds on functions, wrapped values, and fmap; introduces why a wrapped function calls for a different operator.
What you can do after
Apply it via Haskell’s <*> and <$> to combine independent wrapped inputs and recognize when types or dependencies prevent that combination.
How it connects
Places applicatives between functors, which map ordinary functions, and monads, which sequence dependent operations.

Also explained in

Compare how 4 books explain applicative functor →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Coder Cafe. The section links point to the parts of the book it draws on.