[project @ 2002-04-26 12:48:16 by simonmar]
[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
24 newSTRef :: a -> ST s (STRef s a)
25 newSTRef init = ST $ \s1# ->
26     case newMutVar# init s1#            of { (# s2#, var# #) ->
27     (# s2#, STRef var# #) }
28
29 readSTRef :: STRef s a -> ST s a
30 readSTRef (STRef var#) = ST $ \s1# -> readMutVar# var# s1#
31
32 writeSTRef :: STRef s a -> a -> ST s ()
33 writeSTRef (STRef var#) val = ST $ \s1# ->
34     case writeMutVar# var# val s1#      of { s2# ->
35     (# s2#, () #) }
36
37 modifySTRef :: STRef s a -> (a -> a) -> ST s ()
38 modifySTRef ref f = readSTRef ref >>= writeSTRef ref . f
39
40 -- Just pointer equality on mutable references:
41 instance Eq (STRef s a) where
42     STRef v1# == STRef v2# = sameMutVar# v1# v2#
43 \end{code}