Slide 39
Slide 39 text
What about an Applicative instance for the List ADT? Here is
how it looks in Haskell, followed by some examples of its usage.
instance Applicative [] where
pure x = [x]
fs <*> xs = [f x | f <- fs, x <- xs]
class Functor f => Applicative f where
pure :: a -> f a
(<*>) :: f (a -> b) -> f a -> f b
λ (+) <$> [1,2,3] <*> [10,20,30]
[11,21,31,12,22,32,13,23,33]
λ (+) <$> [1,2,3] <*> [10]
[11,12,13]
λ (+) <$> [1,2,3] <*> []
[]
λ max3 x y z = max x (max y z)
λ max3 <$> [6,2] <*> [3,5] <*> [4,9]
[6,9,6,9,4,9,5,9]
λ max3 <$> [6,2] <*> [3] <*> [4,9]
[6,9,4,9]
λ max3 <$> [6,2] <*> [] <*> [4,9]
[]
λ max3 <$> [] <*> [3,5] <*> [4,9]
[]
λ inc n = n + 1
λ twice n = n + n
λ square n = n * n
λ [inc, twice, square] <*> [1,2,3]
[2,3,4,2,4,6,1,4,9]
λ [inc, twice, square] <*> [3]
[4,6,9]
λ [inc, twice, square] <*> []
[]
λ [inc] <*> [1,2,3]
[2,3,4]
λ [] <*> [1,2,3]
[]
λ :type (,)
(,) :: a -> b -> (a, b)
λ (,) <$> ['a','b'] <*> [1,2]
[('a',1),('a',2),('b',1),('b',2)]
λ [(+),(*)] <*> [10,20,30] <*> [1,2]
[11,12,21,22,31,32,10,20,20,40,30,60]
λ [(+),(*)] <*> [10,20,30] <*> [2]
[12,22,32,20,40,60]
λ [(+),(*)] <*> [10] <*> [1,2]
[11,12,10,20]
λ [(+),(*)] <*> [] <*> [1,2]
[]
λ [(+),(*)] <*> [10,20,30] <*> []
[]
λ [(+)] <*> [10,20,30] <*> [1,2]
[11,12,21,22,31,32]
λ [] <*> [10,20,30] <*> [1,2]
[]