classFunctor f where
fmap :: (a -> b) -> f a -> f b
Restriction
fmap id = id
fmap (p . q) = (fmap p) . (fmap q)
Built-in
instanceFunctorIOwhere
fmap f action = do
result <- action
return (f result)
instanceFunctor((->) r) where
fmap f g = (\x -> f (g x))
instanceFunctor((->) r) where
fmap = (.)
Applicative
Definition
class(Functorf) => Applicative f where
pure :: a -> f a
(<*>) :: f (a -> b) -> f a -> f b
(<$>) :: (Functor f) => (a -> b) -> f a -> f b
f <$> x = fmap f x
Restrication
pure id <*> v = v
pure (.) <*> u <*> v <*> w = u <*> (v <*> w)
pure f <*> pure x = pure (f x)
u <*> pure y = pure ($ y) <*> u
Built-in
instanceApplicativeMaybewhere
pure = JustNothing <*> _ = Nothing
(Just f) <*> something = fmap f something
instanceApplicative [] where
pure x = [x]
fs <*> xs = [f x | f <- fs, x <- xs]
instanceApplicativeIOwhere
pure = return
a <*> b = do
f <- a
x <- b
return (f x)
instanceApplicative((->) r) where
pure x = (\_ -> x)
f <*> g = \x -> f x (g x)
instanceApplicativeZipListwhere
pure x = ZipList (repeat x)
ZipList fs <*> ZipList xs = ZipList (zipWith (\f x -> f x) fs xs)
Application
liftA2 :: (Applicative f) => (a -> b -> c) -> f a -> f b -> f c
liftA2 f a b = f <$> a <*> b
sequenceA :: (Applicative f) => [f a] -> f [a]
sequenceA [] = pure []
sequenceA (x:xs) = (:) <$> x <*> sequenceA xs