How to generate a list containing a given number of random numbers within a range in Haskell?

I know how to generate one random number in a given range, a list of random numbers, a list that contains a given number of random numbers, but NOT a list that contains a given number of random numbers within a range. Can someone help me with this?

This code (extracted from haskell.org) generates a list of 10 random numbers, but I need to give a range, any ideas on how to edit this to give a range?

import System.Random import Data.List main = do seed <- newStdGen let rs = randomlist 10 seed print rs randomlist :: Int -> StdGen -> [Int] randomlist n = take n . unfoldr (Just . random) 
+4
source share
2 answers
 randomList :: (Random a) => (a,a) -> Int -> StdGen -> [a] randomList bnds n = take n . randomRs bnds 

Using randomRs from System.Random .

+11
source

quickcheck can also be used to generate random numbers and actually really good combinators, which make it more understandable to formulate the generator.
To use it, you just need to import one module:

 import Test.QuickCheck 

The definition of the generator can be performed as follows:

 t :: Int -> (Int,Int) -> Gen [Int] tnr = vectorOf n (choose r) 

To run this generator, you can use sample' :

 randomList nr = head `fmap` (sample' $ tnr) 
+5
source

Source: https://habr.com/ru/post/1394746/


All Articles