Haskell and random numbers

后端 未结 4 957
耶瑟儿~
耶瑟儿~ 2021-02-02 13:31

I\'ve been messing with Haskell few days and stumbled into a problem.

I need a method that returns a random list of integers ( Rand [[Int]] ).

So, I defined a ty

4条回答
  •  清酒与你
    2021-02-02 14:00

    If you want to get an infinite list of Integers you're going to run into problems as you won't ever get a StdGen value back out. What you want to do here is split the StdGen first, pass one half out again and 'use up' the other half to generate an infinite list of integers. Something like this:

    infiniteRandomInts :: Rand [Int]
    infiniteRandomInts g = (ints, g2) where
        (g1,g2) = split g
        ints = randoms g1
    

    However, if you then repeat this approach to get an infinite matrix of Integers (which you seem to want, by using Rand [[Int]]), you might run into problems of a statistical nature: I don't know how well StdGen deals with repeated splitting. Maybe another implementation of RandomGen might be better, or you could try to use some sort of diagonal walk to turn a [Int] into a [[Int]].

提交回复
热议问题