[Haskell-cafe] class Ref...

Bulat Ziganshin bulatz at HotPOP.com
Tue Jun 7 08:19:36 EDT 2005


Hello Gracjan,

Tuesday, June 07, 2005, 2:25:50 PM, you wrote:
class Monad m =>> Ref m r | m -> r where
GP>      newRef :: a -> m (r a)
GP>      readRef :: r a -> m a
GP>      writeRef :: r a -> a -> m ()

may be the following will be even more interesting:

import Control.Monad
import Data.IORef

infixl 0 =:, +=, -=, =::, <<=
ref = newIORef
val = readIORef
a=:b = writeIORef a b
a+=b = modifyIORef a (\a-> a+b)
a-=b = modifyIORef a (\a-> a-b)
a=::b = ((a=:).b) =<< val a
for :: [a] -> (a -> IO b) -> IO ()
for = flip mapM_

newList = ref []
list <<= x   =  list =:: (++[x])
push list x  =  list =:: (x:)
pop list     =  do x:xs<-val list; list=:xs; return x

main = do
  sum <- ref 0
  lasti <- ref undefined
  for [1..5] $ \i -> do
    sum += i
    lasti =: i
  sum =:: (\sum-> 2*sum+1)
  print =<< val sum
  print =<< val lasti

  xs <- newList
  for [1..3] (push xs)
  xs <<= 10
  xs <<= 20
  print =<< val xs



I use this module to simplify working with references in my program.
The first inteface can be used for IORef/STRef/MVar/TVar and second
for lists and Chan


-- 
Best regards,
 Bulat                            mailto:bulatz at HotPOP.com





More information about the Haskell-Cafe mailing list