Functor (functional programming)



In functional programming, a functor is a design pattern inspired by the definition from category theory that allows one to apply a function to values inside a generic type without changing the structure of the generic type. In Haskell this idea can be captured in a type class:

This declaration says that any type of Functor must support a method, which maps a function over the element(s) of the Functor.

Functors in Haskell should also obey functor laws, which state that the mapping operation preserves the identity function and composition of functions:

(where  stands for function composition).

In Scala a trait can be used:

Functors form a base for more complex abstractions like Applicative Functor, Monad, and Comonad, all of which build atop a canonical functor structure. Functors are useful in modeling functional effects by values of parameterized data types. Modifiable computations are modeled by allowing a pure function to be applied to values of the "inner" type, thus creating the new overall value which represents the modified computation (which might yet to be run).

Examples
In Haskell, lists are a simple example of a functor. We may implement fmap as

A binary tree may similarly be described as a functor:

If we have a binary tree tr :: Tree a and a function f :: a -> b, the function fmap f tr will apply f to every element of tr. For example, if a is Int, adding 1 to each element of tr can be expressed as fmap (+ 1) tr.