Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random number function

Tags:

haskell

I'm trying to get a function that generate a random number, this is what I have so far:

getRandom :: Int -> Int -> Int
getRandom x y = do
    z <- randomRIO( x, y )

This code give me the following error:

The last statement in a 'do' block must be an expression

Now I understand this error, but I don't understand the solution.

I tried:

return z

But it doesn't work.

P.S. I'm very VERY new to Haskell

like image 354
TurnsCoffeeIntoScripts Avatar asked Aug 15 '26 11:08

TurnsCoffeeIntoScripts


1 Answers

A do block can't end in a binding. They desugar to something like

getRandom = randomRIO (x, y) >>= \z ->

which is obviously an error! If you want to just use the result of randomRIO

getRandom x y = randomRIO (x, y)

works fine. Additionally, if you just want a random number,

getRandom :: IO Integer
getRandom = randomIO

works.

like image 169
Daniel Gratzer Avatar answered Aug 18 '26 02:08

Daniel Gratzer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!