Jump to content

Functor (functional programming)

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by 79.247.88.222 (talk) at 19:32, 17 October 2022 (External links: capitalize links). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

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

This idea is encoded in Haskell using type class

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

with conditions called functor laws,

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. Functors are very useful in modeling functional effects to apply a function to computations that did not yet finish.

Functors form a base for more complex abstractions like Applicative, Monad, Comonad.

In C++, the name functor is commonly used to refer to a function object, even though the ISO/IEC 14882 standard specification itself exclusively uses the latter term.