Examples-0.1.0: Haskell code examples
Copyright© Frank Jung 2024
LicenseGPL-3.0-only
Safe HaskellSafe-Inferred
LanguageHaskell2010

Contravariant

Description

From Covariance, contravariance, and positive and negative position and What is a contravariant functor?

The implementation of the function-result fmap and the function-argument contramap are almost exactly the same thing: just function composition (the . operator). The only difference is on which side you compose the adaptor function

fmap :: (r -> s) -> (a -> r) -> (a -> s)
fmap adaptor f = adaptor . f
fmap adaptor = (adaptor .)
fmap = (.)

contramap' :: (b -> a) -> (a -> r) -> (b -> r)
contramap' adaptor f = f . adaptor
contramap' adaptor = (. adaptor)
contramap' = flip (.)

Note that contramap' is not the same as contramap from Contravariant. As you can't make a '-> r' an actual instance of Contravariant in Haskell code simply because the a is not the last type parameter of (->). Conceptually it works perfectly well, and you can always use a newtype wrapper to swap the type parameters and make that an instance (the contravariant defines the the Op type for exactly this purpose).

Synopsis

Types

newtype MakeString a Source #

A contravariant functor.

Constructors

MakeString 

Fields

Instances

Instances details
Contravariant MakeString Source #

Map covariant functor over MakeString.

Instance details

Defined in Contravariant

Methods

contramap :: (a' -> a) -> MakeString a -> MakeString a' #

(>$) :: b -> MakeString b -> MakeString a #

Functions

plus3ShowInt :: MakeString Int Source #

Show an integer plus 3. Compare this with the following code: plus3ShowInt = MakeString (show . (+ 3)) The contramap function is a more general way to compose the function.

showInt :: MakeString Int Source #

Show an integer.