Why can applicative functors have side effects, but functors can't?

后端 未结 4 1448
既然无缘
既然无缘 2020-12-29 07:03

I\'m feeling rather silly asking this question, but it\'s been on my mind for a while and I can\'t find any answers.

So the question is: why can applicative functors

4条回答
  •  爱一瞬间的悲伤
    2020-12-29 07:47

    Let's first rename side effects to effects. All kinds of values can have effects. A functor is a type that allows you to map a function over whatever is produced by that effect.

    When a functor is not applicative it doesn't allow you to use a certain composition style for the effects. Let's pick a (contrived) example:

    data Contrived :: * -> * where
        AnInt :: Int -> Contrived Int
        ABool :: Bool -> Contrived Bool
        None  :: Contrived a
    

    This is easily a functor:

    instance Functor Contrived where
        fmap f (AnInt x) = AnInt (f x)
        fmap f (ABool x) = ABool (f x)
        fmap _ None      = None
    

    However, there is no sensible implementation for pure, so this type is not an applicative functor. It is similar to Maybe in that it has the effect that there may not be a result value. But you can't compose it using applicative combinators.

提交回复
热议问题