[Haskell] ST/STRef vs. IO/IORef

Cale Gibbard cgibbard at gmail.com
Wed Aug 3 03:35:49 EDT 2005


Well, what to do with your computation depends on what that
computation is actually doing. Is the IO really critical to your
algorithm, or can it be done separately? Remember that pure
computation is lazy and so you can save yourself from interleaving a
lot of IO in with generating the data, if you are, for example,
printing it as it is computed.

Basically, the distinction between ST and IO you should worry about is
the same as the one between pure values and IO. You don't want lots of
computations in the IO monad, because IO computations are harder to
reason about; it's harder to make guarantees about what they do.

ST computations should be thought of as computing pure functions,
similar to how ordinary Haskell functions would, except that they may
have multiple named state variables which are carried along during the
computation, and permit an imperative style of programming, for when
that is more natural. (Various graph algorithms, for instance.)

As far as I can tell, stToIO shouldn't be needed in ordinary
programming. runST will serve quite well to extract a value from an ST
computation.

If what you are doing is fundamentally IO, and not just computing some
function, then you should write your computation in the IO monad. Note
that from the IO monad, you can hook up some pure computations (plain
functions, ST, etc.) to do whatever kind of processing is needed to
get from input to output. For this reason, when writing code in the IO
monad, one should only really have to worry about the input and output
to be performed.

I hope this is useful,
- Cale

On 02/08/05, Srinivas Nedunuri <nedunuri at cs.utexas.edu> wrote:
>  
> Hello, I have some code that manipulates STRefs within the ST monad. All
> good and fine, until I come across some computation that uses lets say IO
> and everything skids to a halt. At this point I have 3 choices: 
>   
> 1. Define a ST State Transformer monad and do all my previous ST
> computations in that 
> 2. convert all subsequent ST computations into IO computations using stToIO 
> 3. stop using the ST monad and do everything in the IO monad 
>   
> I was wondering what advice folks had. In particular, what are the
> disadvantages to doing everything in the IO monad - ie why even bother with
> the ST monad? 
>   
> Any help appreciated 
>   
> cheers 
>   
> _______________________________________________
> Haskell mailing list
> Haskell at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell
> 
> 
>


More information about the Haskell mailing list