Get random numbers in F#

ぃ、小莉子 提交于 2019-12-06 14:09:57

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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!