Functors and Mappable Types
You'll learn how to apply functions uniformly to values wrapped in contexts without unpacking them manually.
What Is a Functor?
A functor is any type that holds a value (or values) and provides a way to apply a function to what's inside while preserving the outer structure. Think of it like a gift box: you can transform the contents without destroying or replacing the box itself.
The key operation is usually called map (or fmap in some languages). It takes a function and applies it to the wrapped value(s), returning a new wrapped result of the same type.
Why Does This Matter?
Imagine you have optional values, lists, or any container-like type. Instead of manually checking if a value exists, extracting it, transforming it, and re-wrapping it, a functor lets you say: "apply this transformation, whatever the context."
For example:
- A list of numbers can be mapped to a list of their squares
- An optional value can be mapped to transform the value inside (if present)
- A result type can apply a function only if it represents success
The Functor Contract
A proper functor must satisfy two laws:
- Identity: Mapping the identity function returns the original structure unchanged
- Composition: Mapping function
gthenfequals mapping their compositionf(g(x))
These laws ensure predictable, composable behavior.
Plain-English Example
If you have a box containing 5, and you map "add 3" over it, you get a box containing 8. The box itself didn't change—only its contents transformed according to your function.
Key Takeaway: Functors let you apply transformations uniformly across wrapped values, preserving structure and enabling clean composition of operations without manual unwrapping logic.