[Haskell-cafe] IO and State (was Re: [Haskell] Re: Global Variables and IO initializers)

Iavor S. Diatchki diatchki at cse.ogi.edu
Mon Nov 8 13:38:54 EST 2004


Hello,

Just wanted to point out that the suggested idea is not quite correct.
(well that has to be quantiifed a bit, see bellow)

Krasimir Angelov wrote:

>--- Ben Rudiak-Gould
><Benjamin.Rudiak-Gould at cl.cam.ac.uk> wrote:
>  
>
>>This is solved by merging the IO and ST monads,
>>something that ought to 
>>be done anyway:
>>
>>    type IO = ST RealWorld
>>    type IORef a = Ref RealWorld a
>>    type STRef s a = Ref s a
>>    
>>


It is not (should not be?) the case that IO = ST RealWord, as IO is not 
a state monad as we understand it.
In a state monad, the changes to the state are all in the program, i.e. 
one can always
point to the part of the program that modified the state.
On the other hand, the "state" of the RealWorld can change on its own,
without anything in the program affecting it.
I guess this is similar to "volatile" state in C.
For example, one might expect the following rule in a state monad:

do x <- readSTRef r
     y <- readSTRef r
     f x y
=
do x <- readSTRef r
     f x x

But this is not true for the IO monad, as for example reading a file 
twice does not guarantee
that you will get the same result, even if no part of the program ever 
wrote to the file.

Now the above law already doesn't hold when all GHC extensions are used,
as when concurrency is present we cannot assume that nobody modified the 
state concurrently.
As a result all pointers in GHC probably behave as if they were 
"volatile", which is not very nice.

I think that inherently there are two concepts here, and I see no point 
in mixing them
(even though they are already a bit mixed up, because of stToIO).
The one is the usual sequential state that we know and love (and I think 
we use that a lot of the time).
In the sequential state the above optimization is one of the laws 
specifying the monad.
The other concept is that of "volatile" or concurrent state, and then 
the law doesn't hold.

The two monads have a very similar inetrafce (reading and wrinting 
pointers, and creating new pointers)
but the laws that the operations satisfy are different.

-Iavor











More information about the Haskell-Cafe mailing list