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 instance | Context it represents | Effect of map |
|---|---|---|
| List or array | Zero or more values | Applies the function to every element, keeps length and order |
| Maybe or Option | A value that may be absent | Applies the function if a value exists, otherwise stays empty |
| Either or Result | A success or an error | Transforms the success value, passes the error through untouched |
| Future or Promise | A value available later | Schedules the function to run when the value arrives |
| Function from a fixed input | A computation awaiting input | Composes the mapped function after the existing one |
| Parser | A rule that consumes input | Transforms the parsed result without changing what is consumed |
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.
| Law | Equation | Practical guarantee |
|---|---|---|
| Identity law | fmap id == id | Mapping does not alter structure on its own |
| Composition law | fmap (g . f) == fmap g . fmap f | Two passes can be fused into one pass safely |
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.
| Abstraction | Core operation | What it can express | What it cannot express |
|---|---|---|---|
| Functor | fmap | Transform values inside one context | Combine two independent contexts |
| Applicative | pure and ap | Combine independent contexts, run them in parallel | Choose the next step from a previous result |
| Monad | pure and bind | Sequence steps where later steps depend on earlier ones | Inspect future steps before running them |
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.
| Variant | Mapping signature | Typical use |
|---|---|---|
| Covariant functor | (a -> b) -> f a -> f b | Containers, results, asynchronous values |
| Contravariant functor | (b -> a) -> f a -> f b | Predicates, comparators, serializers |
| Bifunctor | Maps two type parameters | Either, tuples, error and success channels |
| Profunctor | Contravariant input, covariant output | Functions, lenses, data pipelines |
| Traversable functor | Map with an effect, then flip layers | Validating every element of a list |
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.
| Mistake | Consequence | Remedy |
|---|---|---|
| Side effects inside the mapped function | Behavior depends on evaluation order or laziness | Keep mapped functions pure, move effects elsewhere |
Using map where flatMap is needed | Nested results such as an option of an option | Use bind or flatten when the function returns a context |
| Writing an instance that drops elements | Identity law broken, refactoring changes results | Test both laws with generated data |
| Calling a set map a lawful functor | Equal outputs collapse and change size | Document the deviation or use a list |
| Mapping over a Promise expecting laziness | Work starts immediately on creation | Use a lazy task type when deferral matters |
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.