[Haskell-cafe] Sequencing Operations in a Monad

SevenThunders mattcbro at earthlink.net
Mon Sep 17 22:01:58 EDT 2007

Paul Johnson-2 wrote:
> SevenThunders wrote:
>> Unfortunately if I wrap my  matrix references in the IO monad, then at
>> best
>> computations like 
>> S = A + B are themselves IO computations and thus whenever they are
>> 'invoked' the computation ends up getting performed repeatedly contrary
>> to
>> my intentions.  
> This sounds like a case for the infamous performUnsafeIO.  The reason 
> this is "unsafe" is that the compiler assumes that the IO computation it 
> wraps has no visible side effects, so it doesn't matter when it is 
> performed or how many times it gets performed.  If your IO computation 
> indeed has this nature then you are OK, but its up to you to make sure 
> of this.
> Paul.
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe

In the end I went witth the performUnsafeIO 'solution'.  It seems
satisfactory but it is far from perfect. My matrices are stored in the C
world as pointers on a stack.  In Haskell land I only attempted to
'guarantee' that the contents of the referred matrices were referentially
transparent.  Thus, in theory, the stack order could change with function
application order but the 'contents' of the matrices remain the same.  For
those routines that do alter current variables I force the output into the
IO monad.

There are two main problems with this approach.  The first is that if a
computation generates a new matrix by pushing it on to the stack,  a problem
might arise if one of it's dependent input matrices has not been evaluated
yet and if it to requires a new matrix to be pushed on to the stack.  Thus
the output matrix could be 'pushed' prior to the dependent matrices.  This
sort of thing happens all the time with lazy evaluation.  So my fix here is
to write my low level routines with a lot of strictness annotations  using
$! and seq, wherever possible, as well as to force argument evaluation by
sequencing them first in the IO monad.  So far so good, but it is not
perfect,  one has to always keep this limitation in mind.

The second problem is that it is necessary to maintain complete control over
the C stack, allowing the library user to completely trash the stack if not
careful, and utterly destroy referential transparency.  Again one has to
keep this in mind whenever stack manipulations or clearing variables off the

Still with these limitations, it looks like Haskell is going to make things
reasonably nice.
View this message in context: http://www.nabble.com/Sequencing-Operations-in-a-Monad-tf4446047.html#a12748654
Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com.

More information about the Haskell-Cafe mailing list