Haskell and random numbers

后端 未结 4 1013
耶瑟儿~
耶瑟儿~ 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:08

    Using monadic notation, you should be able to write something like

    randomList gen = do
        randomLength <- yourRandomInteger
        loop gen (randomLength + 1)
     where
        loop gen 1 = gen
        loop gen n = do { x <- gen; xs <- loop gen (n - 1); return (x:xs) }
    

    And with this

    randomInts :: Rand [Int]
    randomInts = randomList yourRandomInteger
    
    randomLists :: Rand [[Int]]
    randomLists = randomList randomInts
    

    Concerning the monadic computations itself, take a look at this article. Note that random generators are pure, you shouldn't need any IO just for this purpose.

提交回复
热议问题