简体   繁体   中英

Get random numbers in F#

I have the following function in F#:

let randomCh () = 
        let random = Random()
        alph.Chars (random.Next (alph.Length - 1));

This function returns same value each time. I had same problem in C#, and solution very simple: create just one Random object like this:

    var rnd = new Random();

    for (int i = 0; i < 10; i++)
        Console.WriteLine(rnd.Next(10));

How can I reach same behaviour in F#: get each time random value?

Well your C# code doesn't define a function whereas your F# does; you could have the same problem in C#. You should either refactor your random definition out of the randomCh function, or bind randomCh to a function after initializing random :

let alph = "abcdefg"

let randomCh = 
    let random = Random()
    fun () -> alph.Chars (random.Next (alph.Length - 1))

printfn "%O" <| randomCh()
printfn "%O" <| randomCh()

Just like in C#, you should pull the creation of the random outside of your function. This will prevent you from creating a new Random generator each call. By default, Random uses the current system clock to seed itself - if you call a function, with the random instance inside of it, quickly in succession, you can seed the random with the same time stamps, effectively giving you the same sequence.

By moving it outside of the function, you will reuse the same random instance, and avoid that:

let random = Random()

let randomCh () =         
    alph.Chars (random.Next (alph.Length - 1));

// Calling randomCh() repeatedly will now give different values each time

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