What advantage does Monad give us over an Applicative?

后端 未结 8 587
心在旅途
心在旅途 2020-12-02 11:16

I\'ve read this article, but didn\'t understand last section.

The author says that Monad gives us context sensitivity, but it\'s possible to achieve the same result

8条回答
  •  一整个雨季
    2020-12-02 12:02

    With Applicative, the sequence of effectful actions to be performed is fixed at compile-time. With Monad, it can be varied at run-time based on the results of effects.

    For example, with an Applicative parser, the sequence of parsing actions is fixed for all time. That means that you can potentially perform "optimisations" on it. On the other hand, I can write a Monadic parser which parses some a BNF grammar description, dynamically constructs a parser for that grammar, and then runs that parser over the rest of the input. Every time you run this parser, it potentially constructs a brand new parser to parse the second portion of the input. Applicative has no hope of doing such a thing - and there is no chance of performing compile-time optimisations on a parser that doesn't exist yet...

    As you can see, sometimes the "limitation" of Applicative is actually beneficial - and sometimes the extra power offered by Monad is required to get the job done. This is why we have both.

提交回复
热议问题