Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Right Apply

For a List, why does right apply (*>) behave as repeating and appending the second argument n times, where n is the length of the first argument?

ghci> [1,2,3] *> [4,5]
[4,5,4,5,4,5]
like image 558
Kevin Meredith Avatar asked Mar 17 '23 18:03

Kevin Meredith


1 Answers

The *> operator is defined, by default, as

xs *> ys = id <$ xs <*> ys

which in turn translates, by default, to

const id <$> xs <*> ys

That is, it replaces each element of xs with id to get xs' and then calculates xs' <*> ys. [] is a Monad instance, where (=<<) = concatMap. One of the laws of Applicative lays out the relationship between Applicative and Monad instances:

pure = return
fs <*> as = fs `ap` as = fs >>= \f -> as >>= \a -> f a

For lists, this is

fs <*> as = [f a | f <- fs, a <- as]

So *> for lists is ultimately determined by the Monad instance.

Note that there is another very sensible Applicative instance for lists, which is made available through a newtype in Control.Applicative:

newtype ZipList a = ZipList [a]
instance Applicative ZipList where
  pure = repeat
  (<*>) = zipWith ($) 
like image 157
dfeuer Avatar answered Mar 23 '23 17:03

dfeuer