Applicative functors
import Control.Applicative
typeclass
定义如下:
class (Functor f ) => Applicative f wherepure :: a -> f a(<*>) :: f (a -> b) -> f a -> f b
Applicative状态下Maybe的instance:
instance Applicative Maybe wherepure = JustNothing <*> _ = Nothing(Just f) <*> something = fmap f something
Applicative状态下[ ](列表)的instance:
instance Applicative [] wherepure x = [x]fs <*> xs = [f x | f <- fs, x <- xs]
Applicative状态下IO的instance:
instance Applicative IO wherepure = returna <*> b = dof <- ax <- breturn (f x)
Applicative状态下ZipList的instance:
instance Applicative ZipList wherepure x = ZipList (repeat x)ZipList fs <*> ZipList xs = ZipList (zipWith (\f x -> f x) fs xs)
注意:<*>的第一个参数必须带Just,而<$>的第一个参数只需要是一个函数
(<*>) :: f (a -> b) -> f a -> f b(Just f) <*> something = fmap f something(<$>) :: (Functor f) => (a -> b) -> f a -> f bf <$> x = fmap f x
如何直接调用Applicative状态下的类型?如下:(通过类型标注)
ghci > pure "Hey" :: [String][ "Hey" ]ghci > pure "Hey" :: Maybe StringJust "Hey"ghci> pure "Hey" :: IO String
"Hey"