There are good answers here, but I felt a more complete answer would show very simply how to get and use random numbers in Haskell, in a way that would make sense to imperative programmers.
First, you need a random seed:
import System.Random
newRand = randomIO :: IO Int
Because newRand
is of type IO Int
and not Int
, it cannot be used as a function parameter. (This preserves Haskell functions as pure functions that will always return the same result on the same input.)
We can, however, simply enter newRand
in GHCI and get a unique random seed each time. This is possible only because newRand
is of type IO
and is not a standard (immutable) variable or function.
*Main> newRand
-958036805781772734
We can then copy and paste this seed value into a function that creates a list of random numbers for us. If we define the following function:
randomList :: Int -> [Double]
randomList seed = randoms (mkStdGen seed) :: [Double]
And paste in the given seed when the function is run in GHCI:
*Main> take 10 randomList (-958036805781772734)
[0.3173710114340238,0.9038063995872138,0.26811089937893495,0.2091390866782773,0.6351036926797997,0.7343088946561198,0.7964520135357062,0.7536521528870826,0.4695927477527754,0.2940288797844678]
Notice how we get the familiar values from 0 to 1 (exclusive). Instead of generating a new random number each iteration like we would in an imperative language, we generate a list of random numbers ahead of time and use the head of the tail of the list on each successive recursion. An example:
pythagCheck :: [Double] -> [Double] -> [Int]
pythagCheck (x:xs) (y:ys)
| (a^2) + (b^2) == (c^2) = [a, b, c]
| otherwise = pythagCheck xs ys
where aplusb = ceiling (x * 666)
a = ceiling (y * (fromIntegral (aplusb - 1)))
b = aplusb - a
c = 1000 - a - b
Creating two lists ahead of time and feeding them in as parameters allows us to search for the (one and only!) Pythagorean triple where a + b + c = 1000. You would, of course, want to use a different random seed for each list:
*Main> newRand
3869386208656114178
*Main> newRand
-5497233178519884041
*Main> list1 = randomList 3869386208656114178
*Main> list2 = randomList (-5497233178519884041)
*Main> pythagCheck list1 list2
[200,375,425]