Typo
[packages/base.git] / Data / STRef.hs
1 {-# LANGUAGE Trustworthy #-}
2
3 -----------------------------------------------------------------------------
4 -- |
5 -- Module : Data.STRef
6 -- Copyright : (c) The University of Glasgow 2001
7 -- License : BSD-style (see the file libraries/base/LICENSE)
8 --
9 -- Maintainer : libraries@haskell.org
10 -- Stability : experimental
11 -- Portability : non-portable (uses Control.Monad.ST)
12 --
13 -- Mutable references in the (strict) ST monad.
14 --
15 -----------------------------------------------------------------------------
16
17 module Data.STRef (
18 -- * STRefs
19 STRef, -- abstract
20 newSTRef,
21 readSTRef,
22 writeSTRef,
23 modifySTRef,
24 modifySTRef'
25 ) where
26
27 import Prelude
28
29 import GHC.ST
30 import GHC.STRef
31
32 -- | Mutate the contents of an 'STRef'.
33 --
34 -- Be warned that 'modifySTRef' does not apply the function strictly. This
35 -- means if the program calls 'modifySTRef' many times, but seldomly uses the
36 -- value, thunks will pile up in memory resulting in a space leak. This is a
37 -- common mistake made when using an STRef as a counter. For example, the
38 -- following will leak memory and likely produce a stack overflow:
39 --
40 -- >print $ runST $ do
41 -- > ref <- newSTRef 0
42 -- > replicateM_ 1000000 $ modifySTRef ref (+1)
43 -- > readSTRef ref
44 --
45 -- To avoid this problem, use 'modifySTRef'' instead.
46 modifySTRef :: STRef s a -> (a -> a) -> ST s ()
47 modifySTRef ref f = writeSTRef ref . f =<< readSTRef ref
48
49 -- | Strict version of 'modifySTRef'
50 --
51 -- /Since: 4.6.0.0/
52 modifySTRef' :: STRef s a -> (a -> a) -> ST s ()
53 modifySTRef' ref f = do
54 x <- readSTRef ref
55 let x' = f x
56 x' `seq` writeSTRef ref x'