I'm having difficulty trying to figure out a way to reason about why the following two, seemingly equivalent definitions of an infinite random number sequence (inf
and inf'
) are evaluated completely differently:
import Control.Monad.Random (Rand, evalRandIO, getRandom)
import System.Random (Random, RandomGen, randomIO)
inf :: (RandomGen g, Random a) => Rand g [a]
inf = sequence (repeat getRandom)
inf' :: (Random a) => IO [a]
inf' = sequence (repeat randomIO)
main = do
i <- evalRandIO inf -- HANGS
putStrLn $ show $ take 5 (i :: [Int])
main' = do
i <- inf' -- OK
putStrLn $ show $ take 5 (i :: [Int])
when called, main'
terminates and prints 5 random integers, whereas main
loops infinitely — what causes sequence . repeat
to be evaluated differently on getRandom
than it does on randomIO
?
Aucun commentaire:
Enregistrer un commentaire