2011-05-19 149 views
6

我想用随机数填充一个列表,并且有难以得到随机数的部分。我现在所打印的是一个随机数字10次,我想要打印出10个不同的随机数字F#得到一个随机数列表

let a = (new System.Random()).Next(1, 1000) 


    let listOfSquares = [ for i in 1 .. 10->a] 
    printfn "%A" listOfSquares 

任何提示或建议?

回答

14
let genRandomNumbers count = 
    let rnd = System.Random() 
    List.init count (fun _ -> rnd.Next()) 

let l = genRandomNumbers 10 
printfn "%A" l 
27

您的代码仅仅让一个随机数,并使用10次,

这种扩展方法可能是有用的:

type System.Random with 
    /// Generates an infinite sequence of random numbers within the given range. 
    member this.GetValues(minValue, maxValue) = 
     Seq.initInfinite (fun _ -> this.Next(minValue, maxValue)) 

然后你可以使用它像这样:

let r = System.Random() 
let nums = r.GetValues(1, 1000) |> Seq.take 10 
+1

+1,很好的使用Seq.initInfinite – gradbot 2011-05-20 00:26:11

2

当我写一个随机的东西饮水机我喜欢用相同的随机数字发生器用于每次调用分配器。你可以在F#中使用闭包(Joel's和ildjarn的答案的组合)。

实施例:

let randomWord = 
    let R = System.Random() 
    fun n -> System.String [|for _ in 1..n -> R.Next(26) + 97 |> char|] 

以这种方式,随机的单个实例被“烘焙到”的功能,与每个呼叫重新使用。

+0

很好的答案,但没有回答这个问题。改变它来产生数字而不是一个字,我想我会更喜欢这个。 – 2014-12-14 08:58:45