Question

I tried to use bang patterns on part of the code in Temporal correlations when employing System.Random (not present when employing System.Random.TF) in order to improve the memory consumption, but it seems that the ghci memory usage still increases at an alarming rate, despite the use of bang patterns. That is if I have the code :

{-# LANGUAGE BangPatterns #-}
module Main where
import System.Random

generateNthGenerator !startGen 0 = startGen
generateNthGenerator !startGen n = generateNthGenerator newGen (n-1)
  where newGen = snd $ ((random startGen) :: (Bool,StdGen)) 

main = do 
  print $ generateNthGenerator (mkStdGen 0) 10000000

Then upon loading this into ghci and running (by typing main in ghci) I find that the memory usage rapidly increases.

I have also observed that this memory increase happens evens for the following bang-patterned factorial code, albeit at a slower rate :

{-# LANGUAGE BangPatterns #-}
module Main where

getFactorialAcc 1 !acc = acc
getFactorialAcc n !acc = getFactorialAcc (n-1) (acc * n)

main = do 
  print $ getFactorialAcc 1000000 1

For this latter code the memory consumption initially stays at about 30MB (for about a minute) before suddenly starting to increase.

No correct solution

OTHER TIPS

Thanks to Jake McArthur (see comment above) the solution to containing the memory usage in the case of the random number generator is to write the code as :

{-# LANGUAGE BangPatterns #-}
module Main where
import System.Random

generateNthGenerator startGen 0 = startGen
generateNthGenerator startGen n = generateNthGenerator newGen (n-1)
  where randTuple = ((random startGen) :: (Bool,StdGen))
        !randBool = (fst randTuple)
        newGen = snd randTuple 

main = do 
  print $ generateNthGenerator (mkStdGen 0) 10000000

Alternatively one can do as Antal S-Z suggested below :

{-# LANGUAGE BangPatterns #-}
module Main where
import System.Random

generateNthGenerator startGen 0 = startGen
generateNthGenerator startGen n = generateNthGenerator newGen (n-1)
  where !(!_, newGen) = (random startGen) :: (Bool,StdGen)

main = do 
  print $ generateNthGenerator (mkStdGen 0) 10000000
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top