Applicative Functors

Page content

Applicative Functor

定義

:i Applicative
class Functor f => Applicative (f :: * -> *) where
  pure :: a -> f a
  (<*>) :: f (a -> b) -> f a -> f b
  GHC.Base.liftA2 :: (a -> b -> c) -> f a -> f b -> f c
  (*>) :: f a -> f b -> f b
  (<*) :: f a -> f b -> f a
  {-# MINIMAL pure, ((<*>) | liftA2) #-}
  	-- Defined in ‘GHC.Base’

首先 Applicative 是個 Functor

規則

The identity law:

pure id <*> v = v

Homomorphism:

pure f <*> pure x = pure (f x)

Interchange:

u <*> pure y = pure ($ y) <*> u

Composition:

u <*> (v <*> w) = pure (.) <*> u <*> v <*> w

一些 Applicative instances

一些例子

:m Control.Applicative

aaa

Prelude> liftA2 (+) (Just 1) (Just 2)
Just 3
Prelude> (+) <$> (Just 1) <*> (Just 2)
Just 3
Prelude> (pure (+)) <*> (Just 1) <*> (Just 2)
Just 3