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]
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 ($)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With