📖 WIPIVERSE

🔍 Currently registered entries: 110,723건

Functor (functional programming)

In functional programming, a Functor is a type class (or interface, depending on the language) that defines a uniform way to map a function over a structure without altering the structure's shape. It represents a computational context that allows the application of a function to values contained within that context.

The fundamental characteristic of a Functor is that it provides a function, typically called fmap (or map, or some language-specific equivalent), which applies a given function to each element within the functor's structure, returning a new functor with the transformed elements. This operation preserves the original structure. The core idea is to apply a function 'inside' the container or context represented by the Functor.

A crucial aspect of Functors is that the fmap operation must obey the Functor laws. These laws ensure that the fmap operation behaves predictably and consistently, making it possible to reason about code that uses Functors. The two primary Functor laws are:

  1. Identity Law: Mapping the identity function over a functor should return the original functor unchanged. That is, fmap(identity, functor) should be equivalent to functor. The identity function is a function that returns its argument unchanged (e.g., identity(x) = x).

  2. Composition Law: Mapping the composition of two functions over a functor should be the same as mapping the first function, and then mapping the second function over the result. That is, fmap(compose(f, g), functor) should be equivalent to fmap(f, fmap(g, functor)), where compose(f, g) represents the functional composition of f and g.

By adhering to these laws, Functors provide a guarantee of structural integrity and predictable transformation behavior, allowing for more robust and maintainable code. Common examples of Functors include Lists (or Arrays), Option/Maybe types, and Trees. While the specific implementation of fmap varies depending on the underlying data structure, the core concept remains the same: applying a function to the values contained within the structure while preserving its fundamental shape.