Why should Applicative be a superclass of Monad?

前端 未结 4 1826
礼貌的吻别
礼貌的吻别 2020-12-04 15:32

Given:

Applicative m, Monad m => mf :: m (a -> b), ma :: m a

it seems to be considered a law that:

mf <*> ma ==         


        
4条回答
  •  没有蜡笔的小新
    2020-12-04 16:18

    Just for the record, the answer to the question in the title is: consider

    sequenceA :: Applicative f, Traversable t => t (f a) -> f (t a)
    join :: Monad m => m (m a) -> m a
    

    What is the type of join . sequenceA?

    1. ATP: Monad m, Traversable m => m (m a) -> m a
    2. Current situation: Applicative m, Monad m, Traversable m => m (m a) -> m a

    Granted, join . sequenceA is a contrived situation, but there are certainly cases where you need a monad, but you'd also like to use the Applicative operations <*>, *>, <*, <**>, etc. Then:

    • Having two separate constraints to capture both operations is annoying.
    • The Applicative names is (IMHO) nicer than those of the traditional monad operations.
    • Having two different names, e.g. ap, >>, <<, etc., is annoying ("oh, you can't use <*> there, that's a Monad not an Applicative"; "oh, you have to use <*> there, that's an Applicative not a Monad").
    • In real monads, the order is really, really important, which means that if >> and *> do different things, then you can't actually use the Applicative syntax, because it'll do something you don't expect.

    So, pragmatically, having an Applicative for every Monad which is compatible with it (in the (<*>) = ap sense) is a really, really good idea.

提交回复
热议问题