2 {-# OPTIONS -fno-implicit-prelude #-}
3 -----------------------------------------------------------------------------
6 -- Copyright : (c) The University of Glasgow, 1994-2002
7 -- License : see libraries/base/LICENSE
9 -- Maintainer : cvs-ghc@haskell.org
10 -- Stability : internal
11 -- Portability : non-portable (GHC Extensions)
13 -- References in the 'ST' monad.
15 -----------------------------------------------------------------------------
17 module GHC.STRef where
22 data STRef s a = STRef (MutVar# s a)
23 -- ^ a value of type @STRef s a@ is a mutable variable in state thread @s@,
24 -- containing a value of type @a@
26 -- |Build a new 'STRef' in the current state thread
27 newSTRef :: a -> ST s (STRef s a)
28 newSTRef init = ST $ \s1# ->
29 case newMutVar# init s1# of { (# s2#, var# #) ->
30 (# s2#, STRef var# #) }
32 -- |Read the value of an 'STRef'
33 readSTRef :: STRef s a -> ST s a
34 readSTRef (STRef var#) = ST $ \s1# -> readMutVar# var# s1#
36 -- |Write a new value into an 'STRef'
37 writeSTRef :: STRef s a -> a -> ST s ()
38 writeSTRef (STRef var#) val = ST $ \s1# ->
39 case writeMutVar# var# val s1# of { s2# ->
42 -- |Mutate the contents of an 'STRef'
43 modifySTRef :: STRef s a -> (a -> a) -> ST s ()
44 modifySTRef ref f = readSTRef ref >>= writeSTRef ref . f
46 -- Just pointer equality on mutable references:
47 instance Eq (STRef s a) where
48 STRef v1# == STRef v2# = sameMutVar# v1# v2#