1 module Apexamples where
3 import Control.Applicative
5 pair :: Applicative f => f a -> f b -> f (a,b)
6 -- pair fa fb = (\x y -> (x,y)) <$> fa <*> fb
7 -- pair fa fb = (,) <$> fa <*> fb
8 -- pair fa fb = liftA2 (,) fa fb
12 {-| Can you implement the following functions?
14 Consider what each function does when f is replaced with each of the types:
17 f = Maybe: the result is Nothing if either of the arguments is; if both are
18 Just the result is Just their pairing.
19 f = []: pair computes the Cartesian product of two lists.
20 f = ZipList: pair is the same as the standard zip function.
21 f = IO: pair runs two IO actions in sequence, returning a pair of their results.
22 f = Parser: pair runs two parsers in sequence (the parsers consume consecutive
23 sections of the input), returning their results as a pair. If either parser fails, the whole thing fails.
26 (*>) :: Applicative f => f a -> f b -> f b
27 mapA :: Applicative f => (a -> f b) -> ([a] -> f [b])
28 sequenceA :: Applicative f => [f a] -> f [a]
29 replicateA :: Applicative f => Int -> f a -> f [a]
33 (*>) :: Applicative f => f a -> f b -> f b
34 fa *> fb = (flip const) <$> fa <*> fb
36 mapA :: Applicative f => (a -> f b) -> ([a] -> f [b])
38 mapA f' (x:xs) = liftA2 (:) (f' x) $ mapA f' xs
40 sequenceA :: Applicative f => [f a] -> f [a]
41 sequenceA [] = pure []
42 sequenceA (x:xs) = (:) <$> x <*> sequenceA xs
43 -- sequenceA (x:xs) = liftA2 (:) x (sequenceA xs)
45 replicateA :: Applicative f => Int -> f a -> f [a]
46 replicateA n x = sequenceA (replicate n x)