Search code examples
haskellcategory-theory

What is a Constant functor?


I am trying to understand Constant Functor from the https://en.wikipedia.org/wiki/Functor website and can not imaging visually.

It would be also good, if someone can show it as a haskell code, what a Constant Functor is and for what is good for.


Solution

  • A constant functor is a functor whose object function is a constant function. In haskell:

    newtype Const r a = Const { unConst :: r }
    
    instance Functor (Const r) where
      fmap _ (Const r) = Const r
    

    It maps every type a to r in a sense, and every function of type a -> b to the identity function on r

    It is good for similar things that the const function is good for! Passing to higher order functions, etc.

    One interesting use case is in the definition of lens based getters.