Kevin Meredith
Kevin Meredith

Reputation: 41909

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]

Upvotes: 4

Views: 322

Answers (1)

dfeuer
dfeuer

Reputation: 48591

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 ($) 

Upvotes: 7

Related Questions