我想在Haskell中生成一個隨機數列表。如何生成Haskell中的隨機數列表
Step 1 : declare an empty Int List
Step 2 : Generate a random number between 1 to 50
Step 3 : Add that number at the end of the List.
Step 4 : Repeat Step 2 and 3 for 5 times.
我已經使用數組寫了代碼。
import System.Random
import Data.Array.IO
main = do
arr <- newArray (1,5) 0 :: IO (IOArray Int Int)
forM_ [1..5] (\i -> do
v <- getStdRandom(randomR (1,50))
writeArray arr i v)
forM_ [1..5] (\i -> do
a <- readArray arr i
print (a))
樣本輸出是這樣的: -
Prelude> main
32
14
27
23
33
如何實現這個使用列表。可能使用MVar或TVar列表。提前致謝。
想想這個的方法並不是說「從一個空列表開始,然後填充它」,而是「一個N個隨機數列表由一個隨機數組成,後跟一個N-1個隨機數列表數字」。你寫的是翻譯你想用Java或C++寫的東西。 – 2014-12-07 14:33:53
[Data.Random.Normal](https://hackage.haskell.org/package/normaldistribution-1.1.0.1/docs/Data-Random-Normal.html)模塊可讓您執行諸如'mkNormals 12345'之類的操作來獲取隨機值的無限列表(12345是種子)。 – 2014-12-07 19:20:46
@ PaulJohnson,謝謝你的建議。 – 2014-12-08 04:37:51