packages feed

ArrayRef-0.1: Examples/Universal.hs

-- This program demonstrates implementation of monad-independent algorithms
-- using Ref and URef classes
import Control.Monad.ST
import Data.Ref

main = do
          -- This section demonstrates running of monad-independent algrorithm
          -- `test_Ref` in IO and ST monads
          test_Ref 3         >>= print
          runST (test_Ref 4) |>  print

          -- This section demonstrates running of monad-independent algrorithm
          -- `test_URef` in IO and ST monads
          test_URef 5         >>= print
          runST (test_URef 6) |>  print


-- Using class 'Ref'
test_Ref init = do
          x <- newRef (init::Int)   -- `newRef` operation will create
                                    --    * IORef in IO monad
                                    --    * STRef in ST monad
          x0 <- readRef x           -- `readRef` and `writeRef` operations
          writeRef x (x0+10)        --   works with references of both types
          readRef x

-- Using class 'URef'
test_URef init = do
          x <- newURef (init::Int)  -- `newURef` operation will create
                                    --    * IOURef in IO monad
                                    --    * STURef in ST monad
          x0 <- readURef x          -- `readURef` and `writeURef` operations
          writeURef x (x0+10)       --   works with references of both types
          readURef x

-- Helper operation
a |> b = b a