a0dba8d080f471ce8a04e7be9f517462c6de5def
[ghc-base.git] / GHC / STRef.lhs
1 \begin{code}
2 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
3 {-# OPTIONS_HADDOCK hide #-}
4 -----------------------------------------------------------------------------
5 -- |
6 -- Module      :  GHC.STRef
7 -- Copyright   :  (c) The University of Glasgow, 1994-2002
8 -- License     :  see libraries/base/LICENSE
9 -- 
10 -- Maintainer  :  cvs-ghc@haskell.org
11 -- Stability   :  internal
12 -- Portability :  non-portable (GHC Extensions)
13 --
14 -- References in the 'ST' monad.
15 --
16 -----------------------------------------------------------------------------
17
18 -- #hide
19 module GHC.STRef where
20
21 import GHC.ST
22 import GHC.Base
23
24 data STRef s a = STRef (MutVar# s a)
25 -- ^ a value of type @STRef s a@ is a mutable variable in state thread @s@,
26 -- containing a value of type @a@
27
28 -- |Build a new 'STRef' in the current state thread
29 newSTRef :: a -> ST s (STRef s a)
30 newSTRef init = ST $ \s1# ->
31     case newMutVar# init s1#            of { (# s2#, var# #) ->
32     (# s2#, STRef var# #) }
33
34 -- |Read the value of an 'STRef'
35 readSTRef :: STRef s a -> ST s a
36 readSTRef (STRef var#) = ST $ \s1# -> readMutVar# var# s1#
37
38 -- |Write a new value into an 'STRef'
39 writeSTRef :: STRef s a -> a -> ST s ()
40 writeSTRef (STRef var#) val = ST $ \s1# ->
41     case writeMutVar# var# val s1#      of { s2# ->
42     (# s2#, () #) }
43
44 -- Just pointer equality on mutable references:
45 instance Eq (STRef s a) where
46     STRef v1# == STRef v2# = sameMutVar# v1# v2#
47 \end{code}