Very slow guards in my monadic random implementation (haskell)

Posted by danpriduha on Stack Overflow See other posts from Stack Overflow or by danpriduha
Published on 2010-04-01T06:21:39Z Indexed on 2010/04/01 6:23 UTC
Read the original article Hit count: 290

Filed under:
|
|

Hi! I was tried to write one random number generator implementation, based on number class. I also add there Monad and MonadPlus instance.

What mean "MonadPlus" and why I add this instance? Because of I want to use guards like here:

--  test.hs       --

import RandomMonad
import Control.Monad
import System.Random 

x = Rand (randomR (1 ::Integer, 3)) ::Rand StdGen Integer

y = do
 a <-x
 guard (a /=2) 
 guard (a /=1)
 return a

here comes RandomMonad.hs file contents:

-- RandomMonad.hs --

module RandomMonad where
import Control.Monad
import System.Random 
import Data.List 
data RandomGen g => Rand g a = Rand (g ->(a,g))  | RandZero

instance (Show g, RandomGen g) => Monad (Rand g)
 where
 return x = Rand (\g ->(x,g))
 (RandZero)>>= _ = RandZero

 (Rand argTransformer)>>=(parametricRandom) =  Rand funTransformer 
  where 
  funTransformer g | isZero x = funTransformer g1
                   | otherwise = (getRandom x g1,getGen x g1)
   where
   x = parametricRandom val
   (val,g1) = argTransformer g
   isZero RandZero = True
   isZero _ = False

instance (Show g, RandomGen g) => MonadPlus (Rand g)
 where
 mzero = RandZero
 RandZero `mplus` x = x
 x `mplus` RandZero = x
 x `mplus` y = x 

getRandom :: RandomGen g => Rand g a ->g ->a
getRandom (Rand f) g = (fst (f g)) 
getGen :: RandomGen g => Rand g a ->g -> g
getGen (Rand f) g = snd (f g)

when I run ghci interpreter, and give following command

getRandom y (mkStdGen 2000000000)

I can see memory overflow on my computer (1G). It's not expected, and if I delete one guard, it works very fast. Why in this case it works too slow?

What I do wrong?

© Stack Overflow or respective owner

Related posts about slow

Related posts about random