Skip to content

Instantly share code, notes, and snippets.

@taisyo7333
Last active August 29, 2015 14:24
Show Gist options
  • Save taisyo7333/59b52c342e4dfc763604 to your computer and use it in GitHub Desktop.
Save taisyo7333/59b52c342e4dfc763604 to your computer and use it in GitHub Desktop.
Haskell : random
import System.Random
import Control.Monad(when)
{-
This is referenced from "Learn You a Haskell for Great Good!"
> prompt sample
Which number in the range from 1 to 10 am I thinking of?
9
Sorry, it was 10
Which number in the range from 1 to 10 am I thinking of?
9
You are correct!!
-}
main = do
gen <- getStdGen
askForNumber gen
askForNumber :: StdGen -> IO ()
askForNumber gen = do
let ( randNumber , newGen ) = randomR (1,10) gen :: (Int,StdGen)
putStrLn $ "Which number in the range from 1 to 10 am I thinking of?"
numberString <- getLine
when ( not $ null numberString ) $ do
let number = read numberString
if randNumber == number
then putStrLn "You are correct!!"
else putStrLn $ "Sorry, it was " ++ show randNumber
askForNumber newGen
import System.Random
-- getStdGen , newStdGen
-- If you use getStdGen 2 times , you can get the same result.
-- In this case , you can use newStdGen instead of getStdGen after the first time you use getStdGen.
main = do
gen <- getStdGen
putStrLn $ take 20 (randomRs ('a','z') gen )
gen' <- newStdGen
putStrLn $ take 20 (randomRs ('a','z') gen' )
import System.Random
-- range from 'a' to 'z'
take 6 $ randomRs ('a','z') (mkStdGen 11)
-- range from 1 to 6 , just like dice.
take 6 $ randomRs (1,6) (mkStdGen 11)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment