In
functional programming
In computer science, functional programming is a programming paradigm where programs are constructed by applying and composing functions. It is a declarative programming paradigm in which function definitions are trees of expressions that ...
, a functor is a
design pattern
A design pattern is the re-usable form of a solution to a design problem. The idea was introduced by the architect Christopher Alexander and has been adapted for various other disciplines, particularly software engineering. The " Gang of Four" b ...
inspired by
the definition from category theory that allows one to apply a
function
Function or functionality may refer to:
Computing
* Function key, a type of key on computer keyboards
* Function model, a structured representation of processes in a system
* Function object or functor or functionoid, a concept of object-orie ...
to values inside a
generic type
Generic programming is a style of computer programming in which algorithms are written in terms of types ''to-be-specified-later'' that are then ''instantiated'' when needed for specific types provided as parameters. This approach, pioneered b ...
without changing the structure of the generic type. In Haskell this idea can be captured in a
type class
In computer science, a type class is a type system construct that supports ad hoc polymorphism. This is achieved by adding constraints to type variables in parametrically polymorphic types. Such a constraint typically involves a type class T a ...
:
class Functor f where
fmap :: (a -> b) -> f a -> f b
with conditions called ''functor laws'' (where
.
stands for
function composition
In mathematics, function composition is an operation that takes two functions and , and produces a function such that . In this operation, the function is applied to the result of applying the function to . That is, the functions and ...
),
fmap id = id
fmap (g . h) = (fmap g) . (fmap h)
In
Scala a
trait
Trait may refer to:
* Phenotypic trait in biology, which involve genes and characteristics of organisms
* Genotypic trait, sometimes but not always presenting as a phenotypic trait
* Trait (computer programming)
In computer programming, a tra ...
can be used:
trait Functor [_
Functors form a base for more complex abstractions like Applicative functor">Applicative Functor
In functional programming, an applicative functor, or an applicative for short, is an intermediate structure between functors and monads. Applicative functors allow for functorial computations to be sequenced (unlike plain functors), but don't allo ...