Search code examples
haskellhaskell-lenslenses

How can Monoid r => Const r of the optic Fold type be generalized to Contravariant + Applicative?


Starting from this Getter type

type Getter s a = forall r. (a -> Const r a) -> s -> Const r s

we need an additional Monoid constraint to obtain a Fold:

type Fold s a = forall r. Monoid r => (a -> Const r a) -> s -> Const r s

But Fold's actual and more general type is

type Fold s a = forall f. (Contravariant f, Applicative f) => (a -> f a) -> s -> f s

I understand that Contravariant is used to exclude Identity and thus ensure that we can only get the value. But I don't understand how Monoid r corresponds to Applicative? Sure, Const is also an Applicative but where is the monoid hidden?

Sorry for this confusing question.


Solution

  • The Monoid instance is hidden in the constraint of the Applicative instance for Const r.

    Const r is only an instance of Applicative if r is an instance of Monoid:

    instance Monoid m => Applicative (Const m) where
       ...