]> git.rkrishnan.org Git - yorgey.git/blob - misc/applicatives2.hs
more notes from week11 lecture notes
[yorgey.git] / misc / applicatives2.hs
1 module Apexamples where
2
3 import Control.Applicative
4
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
9 pair = liftA2 (,)
10
11
12 {-| Can you implement the following functions?
13
14 Consider what each function does when f is replaced with each of the types:
15
16
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.
24
25
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]
30
31 -}
32
33 (*>)       :: Applicative f => f a -> f b -> f b
34 fa *> fb = (flip const) <$> fa <*> fb
35
36 mapA       :: Applicative f => (a -> f b) -> ([a] -> f [b])
37 mapA _ [] = pure []
38 mapA f' (x:xs) = liftA2 (:) (f' x) $ mapA f' xs
39
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)
44
45 replicateA :: Applicative f => Int -> f a -> f [a]
46 replicateA n x = sequenceA (replicate n x)