[Haskell-cafe] Re: Fast Mutable Variables for the IO and ST monads

Simon Marlow simonmarhaskell at gmail.com
Wed Feb 8 06:13:20 EST 2006

Bulat Ziganshin wrote:
> Hello Simon,
> Monday, February 06, 2006, 4:41:50 PM, you wrote:
> SM> The Var class is interesting - basically the equivalent of the MArray
> SM> class for mutable variables.  Is there a reason you couldn't use the 
> SM> same pattern as the MArray class?  MArray of Ptr works fine, but for 
> SM> some reason you couldn't do it with Var, why not?
> quick answer: because it don't use fundeps:
> class (HasBounds a, Monad m) => MArray a e m where
> vs
> class (Monad m) => Var m r a | r->a, m a->r where
> and fundeps used to avoid needing to specify type of created
> reference, as should be done with arrays:
>      main = do arr <- newArray (1,10) 37 :: IO (IOArray Int Int)
>      main = print $ runST
>                        (do arr <- newArray (1,10) 127 :: ST s (STArray s Int Int)
> while in my library one can write the following code:
>           chars  <- newVar (0::Int)
>           inWord <- newVar False

Sure, but you're restricted to one kind of Var per monad.  With MArray, 
we have several array types per monad, and we could also have several 
monads per array type - if, say, you wanted to implement an instance of 
MArray for IOArray in your own IO-based monad, that's possible.  Fewer 
fundeps = more flexibility but more type annotations.

If we were to have overloaded references in the standard libraries, it 
would look strange if the interface wasn't consistent with overloaded 
arrays.  I think you could mitigate the problem by providing 
non-overloaded newIORef/newSTRef operations.

I'd support providing IOURef & STURef types, with overloading similar to 
MArray (MRef).

> btw, i have the counter proposal - automatically convert IORefs of
> simple types to the fast internal variables like the Int automatically
> converted to the Int#. The same applies to automatic conversion of
> arrays to the unboxed arrays

The problem with doing this is you need a pretty beefy strictness 
analyser to be able to tell whether the reference is being used 
strictly, this is far beyond what GHC does (I'm impressed that jhc can 
do this, but I don't think there's much hope for us doing it in GHC).

Better is for the user to request strict references, and have the 
implementation do the unboxing, which is exactly what happens with 
IOUArray.  Furthermore, it's deterministic: if you ask for an IOUArray 
(or IOURef), you're guarnanteed to get unboxing, which is better than 
relying on some complex optimisation to work properly.


More information about the Haskell-Cafe mailing list