[Haskell-cafe] Fast Mutable Variables for the IO and ST monads

Bulat Ziganshin bulatz at HotPOP.com
Sat Feb 4 05:15:43 EST 2006


Hello haskell-cafe,

only for the souls interesting in writing efficient programs :)

i included in this letter my own module used for fast variables -
"DataVariables.hs". and "wc.hs" contains example of using these vars.

DataVariables module contains many interesting beasts but for
optimization purposes newVar/readVar/writeVar is especially
interesting. these primitives mimics IORef interface, supports
Int/Word/Bool variables, works in IO and ST monad and nevertheless
they are compiled to the most-effective GHC primitives. moreover, they
can be used outside GHC (of course, on other compilers just IORef/STRer
are used to implement this)

it was impossible to add Ptr's support with the same interface, so
Ptrs supported by another functions - newPtr/readPtr/writePtr and
don't work in ST monad. in other aspects fast Ptr variables are the
same as fast general variables

if you need to include these variables in data structures, use the
types IntVar/WordVar/BoolVar/"MutPtr a" for the IO monad, and
"MutInt s", "MutWord s", "MutBool s" for the ST monad


another interesting beasts are unboxed Int and Bool values. although
GHC can automatically unbox vars in some cases, using this module will
guarantee unboxing. moreover, some operations such as bit shifts, are
ineffective without explicit unboxing because their definitions don't
use unboxed operations directly, but adds additional checks and
conversions. using types FastInt and FastBool and associated
operations guarantee unboxing on GHC and works on other compilers
(where just boxed values are used to implement these types). one place
from my lib where i used them to speed up program:

putWord32be :: (Stream m h, Integral int, Bits int) => h -> int -> m ()
putWord32be h w = do let n = iUnbox (fromIntegral w)
                     vPutByte h $! iBox ((n >># _ILIT 24)              )
                     vPutByte h $! iBox ((n >># _ILIT 16) &# _ILIT 0xff)
                     vPutByte h $! iBox ((n >># _ILIT  8) &# _ILIT 0xff)
                     vPutByte h $! iBox ((n             ) &# _ILIT 0xff)


-- 
Best regards,
 Bulat                          mailto:bulatz at HotPOP.com
-------------- next part --------------
A non-text attachment was scrubbed...
Name: wc.hs
Type: application/octet-stream
Size: 1184 bytes
Desc: not available
Url : http://www.haskell.org//pipermail/haskell-cafe/attachments/20060204/ffa603c4/wc-0001.obj
-------------- next part --------------
A non-text attachment was scrubbed...
Name: DataVariables.hs
Type: application/octet-stream
Size: 8761 bytes
Desc: not available
Url : http://www.haskell.org//pipermail/haskell-cafe/attachments/20060204/ffa603c4/DataVariables-0001.obj


More information about the Haskell-Cafe mailing list