简体   繁体   中英

Initialize a random sequence that is the same each time you then refer to it in F#

I was looking to take a random sample from a sequence by zipping it to a random infinite sequence and doing quickselect on the second element of tuples, but I hit the problem that a sequence initialized with random integers doesn't stay with the same value from the first time it was evaluated. So for example the following code outputs 5 different lines.

let ran=new System.Random(10001100)
let MySeq=Seq.init 10 (fun i->ran.Next())
for time in 0..4 do (for element in MySeq do printf "%s " (element.ToString()) 
                     do printf "\n")

Is there any way to initialize a sequence with random values so that the values remain constant once evaluated?

If you don't have a hard dependency on mySeq really being a lazy sequence, you can just make it an array instead.

let ran = System.Random(10001100)
let mySeq = Array.init 10 (fun i -> ran.Next())
for time in 0..4 do
    for element in mySeq do
        printf "%O " element 
    printf "\n"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM