I want to generate a list with 26 random integers which sum is 301 with Haskell. I write the following:
import System.Random
f 1 sum = [sum]
f n sum = m : (f (n-1) (sum-m))
where m = randomRIO (0,sum)
but it can’t be compiled! I am confused with IO!
Occurs check: cannot construct the infinite type: a1 = IO a1
In the first argument of `(:)', namely `m'
In the expression: m : (f (n - 1) (sum - m))
In an equation for `f':
f n sum
= m : (f (n - 1) (sum - m))
where
m = randomRIO (0, sum)
The error message is somewhat confusing in this case, but the punchline is that you need to work in the
IOmonad, since it’s usingrandomRIOwhich is inIO, and there is (by design) no way to runIOcode from non-IOcode.