I understand that following will be:
[(+2),(+1)]<*>[1,2,3] == [3,4,5,2,3,4]
I also understand that fmap
is implemented as map
. But how could I mentally map this computation in my head? The first time I saw this I assumed the following:
[(*2),(+1)]<*>[1,2,3] == [4,5,6]
The second time around I though about: [[3,4,5],[2,3,4]]
. But on the other hand <*>
returns an fb
so I knew it wouldn't be possible. So my question is, what are the mental steps to make sense out of this?
fs <*> xs
is more-or-less [fx | f <- fs, x <- xs]
[fx | f <- fs, x <- xs]
. Monads have the Applicative instance
fM <*> xM = do
f <- fM
x <- xM
return (f x)
which corresponds to the list comprehension pretty directly.
要记住这一点,你可能会发现简单地想象<*>
是×
(笛卡尔积)更容易:
[a, b, c] × [x, y, z] == [a x, a y, a z, b x, b y, ...]
Interesting. Does an applicative always have to be the cartesian product? Or is the strategy really a matter of choice. For instance could a "zip" of two lists also be valid? ie:
[F1,F2,F3] <*> [a,b,c] == [F1 a, F2 b, F3 c]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.