
Dear Ivan,
A great explanation you have provided! It is very clear. Thank you so much! (You Haskell folks are so willing to help.) Wish there was something I knew that would be useful to you.
Thank you.
Sincerely,
Richard E. Adams
Applications Developer
Las Vegas Valley Water District
Email: Richard.Adams@lvvwd.com
Tel. (702) 856-3627
-----Original Message-----
From: Ivan Perez [mailto:ivanperezdominguez@gmail.com]
Sent: Friday, February 10, 2012 12:28 PM
To: john@repetae.net
Cc: Richard Adams; haskell-cafe@haskell.org
Subject: Re: [Haskell-cafe] Cannot understand liftM2
To understand how liftM2 achieves the cartesian product, I think one way is to find liftM2's implementation and (>>=) implementation as part of []'s instantiation of the Monad class.
You can find the first in Control.Monad, and the second in the standard prelude.
Lists are monads, and as John (almost) said, liftM2 f x y is equivalent to
liftM2 f m1 m2 = do
x1 <- m1
x2 <- m2
return (f x1 x2)
Which is syntactic sugar (fancy Haskell) for
liftM2 f m1 m2 =
m1 >>= (\x1 -> m2 >>= (\x2 -> return (f x1 x2)))
In the prelude, you can find
instance Monad [] where
m >>= k = foldr ((++) . k) [] m
Fhe right-hand side of (>>=) here is roughly equivalent to concat (map k m).
The last step, which I leave as an exercise to the reader (I always wanted to say that), is use the right hand side of the definition of (>>=) for lists in the right hand side of liftM2 when applied to (,) and two lists.
You can see the type of the function (,) (yes, comma is a function!) by executing, in ghci:
:type (,)
Cheers,
Ivan.
On 9 February 2012 19:23, John Meacham
A good first step would be understanding how the other entry works:
cartProd :: [a] -> [b] -> [(a,b)] cartProd xs ys = do x <- xs y <- ys return (x,y)
It is about halfway between the two choices.
John
On Thu, Feb 9, 2012 at 9:37 AM, readams
wrote: Nice explanation. However, at http://stackoverflow.com/questions/4119730/cartesian-product it was pointed out that this
cartProd :: [a] -> [b] -> [(a, b)] cartProd = liftM2 (,)
is equivalent to the cartesian product produced using a list comprehension:
cartProd xs ys = [(x,y) | x <- xs, y <- ys]
I do not see how your method of explanation can be used to explain this equivalence? Nevertheless, can you help me to understand how liftM2 (,) achieves the cartesian product? For example,
Prelude Control.Monad.Reader> liftM2 (,) [1,2] [3,4,5] [(1,3),(1,4),(1,5),(2,3),(2,4),(2,5)]
Thank you!
-- View this message in context: http://haskell.1045720.n5.nabble.com/Cannot-understand-liftM2-tp30856 49p5470185.html Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com.
_______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
_______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe