liveBook · Manning

Functor

As explained in The Coder Cafe

A functor is a functional abstraction that supports applying a function to a value within a computational context while preserving that context.

A functor lets you apply a function to a value inside a context without manually extracting the value. The result stays in that kind of context. This matters when a value might be absent, as with Maybe, or when there are many values, as in a list. section 3.2.1 section 3.0

In Haskell, fmap performs the mapping. Given an ordinary function such as (+1), it transforms the contents of Just 42 into Just 43. Mapping over Nothing returns Nothing: there is no integer to increment, and the empty context stays empty. section 3.2.1

fmapEx :: Maybe Int -- A function returning a Maybe Int
fmapEx = fmap (+ 1) (Just 42) -- Result: Just 43

The listing shows fmap applying (+1) to Just 42 and returning Just 43. section 3.2.1

One function, several values

The same fmap (+1) applied to [1, 2, 3] returns [2, 3, 4]. The function acts on each element while the result remains a list. section 3.2.1

A functor handles a function outside the context and a value inside it. If the function is wrapped too, an applicative addresses that case; if later steps depend on earlier results, a monad handles the sequencing. Functors are the first step, not a substitute for those stronger patterns. section 3.2 section 3.4

How The Coder Cafe covers it

How deep it goes
Defines context-preserving mapping and works through populated, empty, and list cases; leaves wrapped functions and dependent steps to other abstractions.
Examples
Shows fmap (+1) turning Just 42 into Just 43, preserving Nothing, and transforming [1, 2, 3] into [2, 3, 4].
What it assumes
Assumes familiarity with applying a function to a simple integer; introduces the Haskell Maybe example and its notation briefly.
What you can do after
Apply it via Haskell fmap to transform values in Maybe or a list while retaining the context.
How it connects
Connects functors to Maybe, lists, applicatives, and monads through progressively harder forms of applying functions in contexts.

Also explained in

Compare how 9 books explain 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.