I'm trying to calculate growing list with random number. The basic code is here:
import System.Random
randint :: IO Int
randint = randomRIO (0,1)
type Generation = [Int]
gnext :: Generation -> IO Generation
gnext g = flip (:) g <$> randint
gnext can be more complex.
Now following code behaved as expected:
test1 = do
let b0 = []
b1 <- gnext b0
b2 <- gnext b1
b3 <- gnext b2
b4 <- gnext b3
return [b0, b1, b2, b3, b4]
ghci> test1
[[],[0],[1,0],[1,1,0],[1,1,1,0]]
We can see the n-th list has the (n-1)-th list in its cdr part.
On the other hand, following code failed (because of lazy evaluation, I think).
test2 = sequence $ take 5 $ iterate (gnext =<<) (return [])
ghci> test2
[[],[0],[0,0],[1,0,1],[1,1,1,0]]
This result is completely random.
How can I rewrite test1 code by test2 style?
Thank you.