Created
March 10, 2022 15:24
-
-
Save el-hult/486b9208edff473e1da91260a6d361bc to your computer and use it in GitHub Desktop.
Example on how to generate a lazy stream of random numbers in haskell using System.IO.Unsafe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import System.IO.Unsafe ( unsafeInterleaveIO ) | |
import System.Random ( randomRIO ) | |
import Text.Printf ( printf ) | |
-- | An infinite list of random die rolls, lazily generated | |
-- | |
-- This is dangerous since calling this function steps the global random generator | |
-- not when running the action, but when accessing its result. | |
diceRolls :: IO [Int] | |
diceRolls = do | |
x <- randomRIO (1,6) | |
xs <- unsafeInterleaveIO diceRolls | |
return (x:xs) | |
main :: IO () | |
main = do | |
-- The type of `rolls` is [Int], but accessing elements in that list will have side effects! 🤯 | |
rolls <- diceRolls | |
printf "It took %d rolls to get a 6 on the die." . (+ 1) . length . takeWhile (/= 6) $ rolls |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment