PlayHardGoPro
PlayHardGoPro

Reputation: 2933

Can't generate random numbers

I can't figure out how to generate random number.

Here is how I'm trying to do according to this:

main :: IO ()
main = do
  let
     g <- getStdGen
     bla = randomRs (0, 360) g

Also tried:

main :: IO ()
main = do
  let
    r <- randomIO

then:

parse error on input `<-' Perhaps this statement should be within a 'do' block?

Upvotes: 0

Views: 352

Answers (1)

crockeea
crockeea

Reputation: 21811

I highly recommend one of the many great, free Haskell tutorials, such as Learn You A Haskell or Real World Haskell.

You can find more about do notation here.

To specifically answer your question, you are misusing the let keyword with do notation. The basic rule is: if the answer is in a monad, you should use <- with no let. If the value is not in a monad, write let bla = .... You can write several such statements in a row without duplicating the let keyword:

do
  x <- y :: m a
  let z = z1
      z' = z2
      ...
  w <- w' :: m b
  z <- z' :: m c
...

Your code should be more like:

main :: IO ()
main = do
  g <- getStdGen
  let bla = randomRs (0,360) g

An even better option is to use MonadRandom to hide the generator (state) completely:

include Control.Monad.Random

main :: IO ()
main = do
  bla <- getRandomR (0,360)

Upvotes: 6

Related Questions