ed56bc9970d8ea4e38420e3f90c8cb2d7d947ef1
[ghc-base.git] / GHC / STRef.lhs
1 \begin{code}
2 {-# OPTIONS -fno-implicit-prelude #-}
3 -----------------------------------------------------------------------------
4 -- |
5 -- Module      :  GHC.STRef
6 -- Copyright   :  (c) The University of Glasgow, 1994-2002
7 -- License     :  see libraries/base/LICENSE
8 -- 
9 -- Maintainer  :  cvs-ghc@haskell.org
10 -- Stability   :  internal
11 -- Portability :  non-portable (GHC Extensions)
12 --
13 -- References in the 'ST' monad.
14 --
15 -----------------------------------------------------------------------------
16
17 module GHC.STRef where
18
19 import GHC.ST
20 import GHC.Base
21
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@
25
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# #) }
31
32 -- |Read the value of an 'STRef'
33 readSTRef :: STRef s a -> ST s a
34 readSTRef (STRef var#) = ST $ \s1# -> readMutVar# var# s1#
35
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# ->
40     (# s2#, () #) }
41
42 -- Just pointer equality on mutable references:
43 instance Eq (STRef s a) where
44     STRef v1# == STRef v2# = sameMutVar# v1# v2#
45 \end{code}