How to use getStdGen in function

I am new to haskell, especially in the style of Random, and I was learning tutorials when I came across this.

import System.Random  

main = do  
    gen <- getStdGen  
    putStr $ take 20 (randomRs ('a','z') gen) 

However, when I try to use this in a function, it does not work (ie)

genrandTF:: Int -> StdGen -> [Bool]
genrandTF number gen =  take number (randomRs (True, False) gen)

and calling him through

genrandTF 20 getStdGen

why?

-update -

The error I get is

<interactive>:116:15:
    Couldn't match expected type `StdGen' with actual type `IO StdGen'
    In the second argument of `genrandTF', namely `(getStdGen)'
    In the expression: genrandTF 20 (getStdGen)

When I change it to the IO StdGen type, I cannot compile it when I receive this message:

No instance for (RandomGen (IO StdGen))
  arising from a use of `randomRs'
In the second argument of `take', namely
  `(randomRs (True, False) gen)'
In the expression: take number (randomRs (True, False) gen)
In an equation for `genrandTF':
    genrandTF number gen = take number (randomRs (True, False) gen)
+4
source share
2 answers

This is a common beginner mistake. getStdGenis a value of type IO StdGen; in other words, it is not StdGen, but rather a computer program that, when completed, will contain what Haskell can use as StdGen.

, StdGen ( unsafePerformIO - , Haskell), . (, Haskell I/O - Haskell, -.)

, , :

fmap (genrandTF 20) getStdGen

Functor IO.

+3

randomR ( randomRs ):

, , lo > hi

( randomR (lo,hi).

True > False, . (False,True) ( IO).

-2

All Articles