Can a monad be a comonad?

前端 未结 5 1976
孤独总比滥情好
孤独总比滥情好 2020-12-23 17:31

I know what a monad is. I think I have correctly wrapped my mind around what a comonad is. (Or rather, what one is seems simple enough; the tricky part is

5条回答
  •  猫巷女王i
    2020-12-23 17:40

    There are many interesting structures that are both a Monad and a Comonad.

    The Identity functor has been pointed out here by several other people, but there are non-trivial examples.

    The Writer Monad plays a Reader-like role as a Comonad.

    instance Monoid e => Monad ((,) e)
    instance Comonad ((,) e)
    

    The Reader Monad plays a Writer-like role as a Comonad.

    instance Monad ((->) e)
    instance Monoid e => Comonad ((->)e)
    

    Non-empty lists also form both a monad and a comonad and are in fact a special case of a larger construction involving cofree comonads. The Identity case can also be seen as a special case of this.

    There are also various Yoneda and Codensity-like constructions based on Kan extensions, that work to transform monads and comonads, although they favor one or the other in terms of operational efficiency.

    I also have an adapter that converts an arbitrary comonad into a monad transformer. Sadly the opposite conversion isn't possible in Haskell.

    In linear algebra there is a notion of a bialgebra. Ideally if we have something that forms both a Monad and a Comonad and we want to use those operations together without reasoning on a case-by-case basis, one would like to have that return and join are Comonad coalgebras and by extension that extract and duplicate are Monad algebras. If those conditions hold then you can actually reason about code that has both Monad f and Comonad f constraints and mixes the combinators from each without case-by-case reasoning.

提交回复
热议问题