In the paper Tackling the awkward squad, Simon Peyton Jones has provided a "possible implementation" of a Channel
.
type Channel a = (MVar (Stream a) , -- Read end
MVar (Stream a) ) -- Write end (the hole)
type Stream a = MVar (Item a)
data Item a = MkItem a (Stream a)
Now, he implements a function putChan :: Channel a -> a -> IO ()
like this
putChan (read, write) val
= do { new_hole <- newEmptyVar ;
old_hole <- takeMVar write ;
putMVar write new_hole ;
putMVar old_hole (MkItem val new_hole) }
The function above takes a MVar out of write, then puts an empty MVar into it.
Then it writes to the old_hole it extracted from write.
The question is, why does it write to old_hole? It has been taken out from write and its scope is limited to the current block only, then what difference does it make?