How can I make a counter without Monad?
Nicolas Oury
Nicolas.Oury at lri.fr
Tue Mar 15 19:17:51 EST 2005
Greetings,
In a program, I want to give a unique name to some structures.
As it is the only imperative thing I need, I don't want to use a monad.
I have played with two solutions and have some questions :
* unsafePerformIO :
I create a counter :
counter :: IORef Int
counter = unsafePerformIO (newIORef 0)
{-# NOINLINE counter #-}
and a function to give a unique name:
newNode a = unsafePerformIO $
do
i <- readIORef counter
writeIORef counter (i+1)
return (i,a)
{-# NOINLINE newNode #-}
I now want to write a function :
foo a =
let n = newNode a in
(n,n)
How can I make sure ghc won't reduce it to
foo a = (newNode a, newNode a) ?
* linear implicit parameters
instance Splittable Int where
split n = (2*n,2*n+1)
But I have a problem : the counter value increases exponentially. (I
can only count up to 32 elements...)
Is there another way to split Int?
Are there other ways to implement a counter in Haskell?
Thanks for your help,
Best regards,
Nicolas Oury
More information about the Glasgow-haskell-users
mailing list