F# getting a list of random numbers

2019-01-09 15:23发布

I am trying to fill a list with random numbers and am having diffculty getting the random number part. What I have right now prints out a random number 10 times, what I want is to print out 10 different random numbers

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


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

any tips or suggestions?

标签: f#
4条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-09 15:49

Your code is simply getting one random number and using it ten times.

This extension method might be useful:

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))

Then you can use it like this:

let r = System.Random()
let nums = r.GetValues(1, 1000) |> Seq.take 10
查看更多
来,给爷笑一个
3楼-- · 2019-01-09 15:49
闹够了就滚
4楼-- · 2019-01-09 15:57

When I write a random something dispenser I like to use the same random number generator for each call to the dispenser. You can do that in F# with closures (a combination of Joel's and ildjarn's answer).

Example:

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

In this way, a single instance of Random is 'baked into' the function, reusing it with each call.

查看更多
乱世女痞
5楼-- · 2019-01-09 16:09
let genRandomNumbers count =
    let rnd = System.Random()
    List.init count (fun _ -> rnd.Next ())

let l = genRandomNumbers 10
printfn "%A" l
查看更多
登录 后发表回答