Skip to content

Instantly share code, notes, and snippets.

@el-hult
Created March 10, 2022 15:24
Show Gist options
  • Save el-hult/486b9208edff473e1da91260a6d361bc to your computer and use it in GitHub Desktop.
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
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