Functor

On this page 7

A functor is a type that holds or produces values and provides a structure-preserving map operation, usually called map or fmap, which applies an ordinary function to those values without changing the shape of the container around them. In functional programming, the functor is one of the most widely used abstractions, because it lets developers transform data inside lists, optional values, results, futures and parsers with a single, uniform interface.

The concept comes from category theory, where a functor maps objects and arrows of one category to another while preserving identity and composition. Programmers rarely need the full mathematics, but they rely on the same two guarantees every day: mapping the identity function changes nothing, and mapping two functions in sequence equals mapping their composition.

How a functor maps over a context

A functor works by separating what a value is from the context it lives in. The context may be a collection of many values, a value that might be missing, a value that will arrive later, or a computation that has not yet run. The map operation reaches into that context, applies a plain function of type a -> b to each value present, and returns the same kind of context holding the results.

In Haskell, the abstraction is expressed as a type class with one method, fmap :: (a -> b) -> f a -> f b, where f is a type constructor such as Maybe or List rather than a concrete type. Scala libraries such as Cats define the same interface, and JavaScript developers meet it every time they call Array.prototype.map. The key point is that the function being mapped knows nothing about the container, so one function can be reused across many contexts.

The table below shows how the same mapping step behaves in common functor instances.

Functor instanceContext it representsEffect of map
List or arrayZero or more valuesApplies the function to every element, keeps length and order
Maybe or OptionA value that may be absentApplies the function if a value exists, otherwise stays empty
Either or ResultA success or an errorTransforms the success value, passes the error through untouched
Future or PromiseA value available laterSchedules the function to run when the value arrives
Function from a fixed inputA computation awaiting inputComposes the mapped function after the existing one
ParserA rule that consumes inputTransforms the parsed result without changing what is consumed
Common functor instances and what map does

The functor laws and why they matter

A type is a lawful functor only when its map operation satisfies two functor laws. These laws are not checked by most compilers, so the author of an instance is responsible for them, typically through property-based tests that generate random values and compare both sides of each equation.

The laws below are what make refactoring safe: they guarantee that map only transforms values and never adds, drops, reorders or duplicates them.

LawEquationPractical guarantee
Identity lawfmap id == idMapping does not alter structure on its own
Composition lawfmap (g . f) == fmap g . fmap fTwo passes can be fused into one pass safely
The two functor laws

The composition law has direct performance value. Compilers and libraries use it for map fusion, rewriting two traversals of a large list into a single traversal. The identity law, in turn, rules out implementations that secretly sort, truncate or log values, which would make equational reasoning impossible. In Haskell, parametricity means that any fmap satisfying the identity law automatically satisfies the composition law, but that shortcut does not hold in languages with unrestricted side effects.

Functor compared with applicative and monad

The functor is the weakest member of a hierarchy that continues with the applicative functor and the monad. Each step adds power and imposes more requirements, so choosing the weakest abstraction that solves a problem keeps code more general and easier to reuse.

AbstractionCore operationWhat it can expressWhat it cannot express
FunctorfmapTransform values inside one contextCombine two independent contexts
Applicativepure and apCombine independent contexts, run them in parallelChoose the next step from a previous result
Monadpure and bindSequence steps where later steps depend on earlier onesInspect future steps before running them
Functor, applicative and monad side by side

Every monad is an applicative and every applicative is a functor, but not every functor is a monad. A practical consequence is that functions written against the functor interface accept more types. Developers who reach for monadic flatMap when a plain map is enough lose that generality and often make data dependencies harder to see.

Variants of the functor idea

Programming languages use several specialized functor variants, each defined by how the type parameter flows through the structure. The ordinary functor is technically a covariant functor, because mapping goes in the same direction as the function.

VariantMapping signatureTypical use
Covariant functor(a -> b) -> f a -> f bContainers, results, asynchronous values
Contravariant functor(b -> a) -> f a -> f bPredicates, comparators, serializers
BifunctorMaps two type parametersEither, tuples, error and success channels
ProfunctorContravariant input, covariant outputFunctions, lenses, data pipelines
Traversable functorMap with an effect, then flip layersValidating every element of a list
Functor variants used in practice

A separate meaning exists in other languages, and it is easy to confuse. In C++, a function object that overloads the call operator is often called a functor, and in OCaml and Standard ML a functor is a module-level function that builds a module from another module. Neither usage implies the mapping laws described here.

Common mistakes when using functors

Most functor errors come from treating map as a general-purpose loop rather than a pure transformation. The following table lists frequent problems and their fixes.

MistakeConsequenceRemedy
Side effects inside the mapped functionBehavior depends on evaluation order or lazinessKeep mapped functions pure, move effects elsewhere
Using map where flatMap is neededNested results such as an option of an optionUse bind or flatten when the function returns a context
Writing an instance that drops elementsIdentity law broken, refactoring changes resultsTest both laws with generated data
Calling a set map a lawful functorEqual outputs collapse and change sizeDocument the deviation or use a list
Mapping over a Promise expecting lazinessWork starts immediately on creationUse a lazy task type when deferral matters
Functor pitfalls and remedies

A subtle case is the JavaScript Promise, whose then method behaves like both map and bind because it automatically flattens nested promises. That convenience breaks the strict functor contract and is a frequent source of surprise for developers moving between languages.

A non-technical view

Think of a functor as a box with a rule for changes. You hand it an instruction such as add tax to each price, and the box applies that instruction to whatever is inside. If the box holds ten prices, all ten change. If it is empty, nothing happens and nothing breaks.

The important promise is that the box never changes its own shape. A list stays the same length, a missing value stays missing, and an error stays an error. That predictability is why programmers trust functors to keep data safe while it is being transformed.

A concrete example

A payments team receives exchange rates from an external service. The lookup can fail, so the rate arrives wrapped in a Result type that holds either a number or an error message. The team needs to convert an invoice of 1,200 euros into dollars and round the figure to two decimal places.

Instead of writing nested checks for failure, a developer maps a conversion function and then a rounding function over the Result. When the rate is 1.08, the output is a success holding 1,296.00 dollars. When the service times out, the error simply passes through unchanged and is logged at the edge of the system.

The same two small functions are reused on a list of 400 invoices and on an asynchronous rate stream, with no extra error-handling code. Code review becomes faster because each function can be tested in isolation, and the functor laws guarantee that combining the two steps into one map gives identical results.