What does "MutVar #" mean?
I tried to read and understand the code that implements the Haskell ST monad and I found this code :
{-# LANGUAGE Unsafe #-}
{-# LANGUAGE NoImplicitPrelude, MagicHash, UnboxedTuples #-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.STRef
-- Copyright : (c) The University of Glasgow, 1994-2002
-- License : see libraries/base/LICENSE
--
-- Maintainer : cvs-ghc@haskell.org
-- Stability : internal
-- Portability : non-portable (GHC Extensions)
--
-- References in the 'ST' monad.
--
-----------------------------------------------------------------------------
module GHC.STRef (
STRef(..),
newSTRef, readSTRef, writeSTRef
) where
import GHC.ST
import GHC.Base
data STRef s a = STRef (MutVar# s a)
-- ^ a value of type @STRef s a@ is a mutable variable in state thread @s@,
-- containing a value of type @a@
-- |Build a new 'STRef' in the current state thread
newSTRef :: a -> ST s (STRef s a)
newSTRef init = ST $ \s1# ->
case newMutVar# init s1# of { (# s2#, var# #) ->
(# s2#, STRef var# #) }
-- |Read the value of an 'STRef'
readSTRef :: STRef s a -> ST s a
readSTRef (STRef var#) = ST $ \s1# -> readMutVar# var# s1#
-- |Write a new value into an 'STRef'
writeSTRef :: STRef s a -> a -> ST s ()
writeSTRef (STRef var#) val = ST $ \s1# ->
case writeMutVar# var# val s1# of { s2# ->
(# s2#, () #) }
-- Just pointer equality on mutable references:
instance Eq (STRef s a) where
STRef v1# == STRef v2# = isTrue# (sameMutVar# v1# v2#)
In the above code file, I see the following line of code:
data STRef s a = STRef (MutVar# s a)
A quick search for MutVar#
gave the following results:
- https://hackage.haskell.org/package/primitive-0.4.1/docs/src/Data-Primitive-MutVar.html#MutVar
- https://github.com/ghc/ghc/blob/228ddb95ee137e7cef02dcfe2521233892dd61e0/utils/genprimopcode/Main.hs#L816
My question is: What is it MutVar#
? Why is it not defined anywhere? What does it mean?
source to share
MutVar#
is a primitive type provided by the compiler itself. It is a variable reference and forms the core IORef
and STRef
.
In general, anything that ends with #
is an implementation detail of the GHC. Unless you use low level hacking, you don't need to worry about them. Most of these operations have wrappers (for example ST
) that are easier to use.
You can read more about this in the GHC manual and ghc-prim
.
source to share