Reputation: 14029
In Haskell, I'd like to generate a random list of Int
s and use it throughout my program. My current solution causes the array to be created randomly each time I access/use it.
How can I overcome this problem?
Upvotes: 1
Views: 178
Reputation: 52270
Here is a simple example (@luqui mentioned) you should be able to generalize to your need:
module Main where
import Control.Monad (replicateM)
import System.Random (randomRIO)
main :: IO ()
main = do
randomList <- randomInts 10 (1,6)
print randomList
let s = myFunUsingRandomList randomList
print s
myFunUsingRandomList :: [Int] -> Int
myFunUsingRandomList list = sum list
randomInts :: Int -> (Int,Int) -> IO [Int]
randomInts len bounds = replicateM len $ randomRIO bounds
randomInts
is an IO
-action that will produce you your random list of integers, you see it's use in the very first line of main
s do
-block. Once it is used there the list will stay the same.myFunUsingRandomList
is a very simple example (just summing it) of using such a list in a pure fashion - indeed it just expects a list of integers and I just happen to call it with the random list from main
Upvotes: 2
Reputation: 32309
Follow this example. Then, pass rs
from main
to whatever function needs it.
You can't have a global variable for this without using something like unsafePerformIO
, which, as the name indicates, should not be used. The reason is that picking random numbers is an inherently non-deterministic operation, dependent on the outside IO
state.
Upvotes: 0