获取F#中的随机数 [英] Get random numbers in F#
本文介绍了获取F#中的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在F#中具有以下功能:
I have the following function in F#:
let randomCh () =
let random = Random()
alph.Chars (random.Next (alph.Length - 1));
此函数每次都返回相同的值.我在C#中遇到了同样的问题,解决方法非常简单:仅创建一个Random对象,如下所示:
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));
如何在F#中达到相同的行为:获取每次随机值?
How can I reach same behaviour in F#: get each time random value?
推荐答案
C#代码没有定义函数,而F#却定义了函数.您可能在C#中遇到相同的问题.您应该从randomCh
函数中重构random
定义,或者在初始化random
之后将randomCh
绑定到函数:
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()
这篇关于获取F#中的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文