[Haskell-cafe] Sequencing Operations in a Monad

SevenThunders mattcbro at earthlink.net
Sat Sep 15 03:18:13 EDT 2007

Dominic Steinitz wrote:
>>  If you arrange the types to try to do all the operations inside the IO
>> monad you can't chain together more than 1 binary operation.  eg.
>> do
>>    S <- A + B
>>    Z <- Q * S
>> vs
>> do 
>>    S <-  Q * (A + B)
>> Are there any suggestions for this dilemma?  Am I using the wrong monad
>> for
>> this task?
> I'm not sure if this is what you are asking but isn't liftM2 or some
> variant what you need?
> Dominic.
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe

OK so check out what really happens with liftM2.  Suppose I have an IO
containing an involved matrix computation called s.  For simplicity we might
assume that

s :: IO (Int)   

and the Int is an index into an array containing a bunch of matrices in C
land.  Assume that s is determined by a succession of many IO operations
that have lots of side effects and are fairly computationally intensive. 
Also assume that s is unevaluated.

Now do an operation like

q = liftM2 MultMatrix s s

What happens is that s is 'evaluated' twice when q is evaluated

    qint <- q

That becomes evident when we look at liftM2's definition
liftM2 f  =  \a b -> do { a' <- a; b' <- b; return (f a' b') }

the statements 
a' <- a   and b' <- b will cause s to be evaluated twice.

Therein lies my problem.

View this message in context: http://www.nabble.com/Sequencing-Operations-in-a-Monad-tf4446788.html#a12687963
Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com.

More information about the Haskell-Cafe mailing list