Is it better to define Functor in terms of Applicative in terms of Monad, or vice versa?

前端 未结 5 571
南笙
南笙 2021-02-02 13:25

This is a general question, not tied to any one piece of code.

Say you have a type T a that can be given an instance of Monad. Since every mona

5条回答
  •  感动是毒
    2021-02-02 14:17

    I often choose a reverse approach as compared to the one in Abrahamson's answer. I manually define only the Monad instance and define the Applicative and Functor in terms of it with the help of already defined functions in the Control.Monad, which renders those instances the same for absolutely any monad, i.e.:

    instance Applicative SomeMonad where
      pure = return
      (<*>) = ap
    
    instance Functore SomeMonad where
      fmap = liftM
    

    While this way the definition of Functor and Applicative is always "brain-free" and very easy to reason about, I must note that this is not the ultimate solution, since there are cases, when the instances can be implemented more efficiently or even provide new features. E.g., the Applicative instance of Concurrently executes things ... concurrently, while the Monad instance can only execute them sequentially due to the nature monads.

提交回复
热议问题