[英]How to generate List of random numbers in Haskell
I want to generate a list of random numbers in 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.
I have written the code using an Array. 我已经使用数组编写了代码。
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))
A sample output is like this: - 输出示例如下:-
Prelude> main
32
14
27
23
33
How to implement this using a List. 如何使用列表来实现这一点。 May be using MVar or TVar List.
可能正在使用MVar或TVar List。 Thanks in advance.
提前致谢。
Step 1 : declare an empty
Int
List...步骤1:声明一个空的
Int
List ...
don't do that. 不要那样做 Creating an empty thing an then filling it up is seldom a good idea.
创建一个空的东西然后填充它很少是一个好主意。 Sometimes, for performance reasons, it can be clever to create an uninitialised array (not empty, but "vacuous") and then define the contents after the fact – that's basically what happens in you code.
有时,出于性能原因,创建一个未初始化的数组 (不是空的,而是“空的”)然后在事实之后定义内容可能很聪明-这基本上就是代码中发生的事情。 Also reasonable: starting with an empty
Set
and progressively filling it up; 也很合理:从一个空的
Set
并逐渐填充它; this can be done nicely in a purely-functional state monad. 在纯功能状态的monad中可以很好地做到这一点。
But for lists (or arrays), starting empty never gains you anything; 但是对于列表(或数组),从空开始永远不会给您带来任何好处。 why not properly define the full result list straight away?
为什么不立即正确定义完整的结果列表? It's as simple as this:
就这么简单:
do
...
randList <- forM [1 .. lLength] $ \_i -> randomRIO (1,50)
...
Note that this is not forM_
but forM
, which automatically gathers the results in a list – just what you want! 请注意,这不是
forM_
而是forM
,它会自动将结果收集在列表中–就是您想要的! I don't actually need the index parameter (hence the _
prefix of the i
variable). 我实际上不需要index参数(因此,
i
变量的_
前缀)。 I could also have written mapM (const $ randomRIO (1,50)) [1 .. lLength]
, or indeed simply replicateM lLength $ randomRIO (1,50)
, as user3237465 remarks. 我也可以写
mapM (const $ randomRIO (1,50)) [1 .. lLength]
,或者确实只是replicateM lLength $ randomRIO (1,50)
,作为user3237465的评论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.