Jump to content

Functor (functional programming)

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by PiotrParadzinski (talk | contribs) at 13:01, 1 March 2020 (Add classic reference to Haskell, Scala and basic information). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

In functional programming, a Functor is a design pattern inspired by definition from category theory, that allows for generic type to apply function inside without changing the structure of generic type.

This idea is encoded in Haskell using [type class]

class Functor f where
  fmap :: (a -> b) -> f a -> f b

with conditions

fmap id = id
fmap (g . h) = (fmap g) . (fmap h)

In Scala [higher kinded types] are used

trait Functor[F[_]] {
  def map[A,B](a: F[A])(f: A => B): F[B]
}

Simple examples of this are Option and collection types. Functor is very useful to model functional effects to apply a function to computations that did not yet finish.

Functor is base for more complex abstractions like Applicative, Monad, Comonad.

In C++ name functor is incorrectly refers to function object.