[英]Closures and random numbers in F#
For fun, I am trying to write a simple simulation of the Monty Hall problem problem using F#. 为了好玩,我试图用F#编写一个简单的Monty Hall问题模拟。
I have created a function getShow which returns an array of three booleans (representing doors), one of which is randomly true (it has a car behind it) and the other two false. 我创建了一个函数getShow ,该函数返回一个由三个布尔值组成的数组(代表门),其中一个布尔值为true(它后面有辆汽车),而另外两个为false。
let getShow =
let doorWithCar = System.Random().Next(3)+1
[|for door in 1..3 -> door = doorWithCar|]
Now when I try to get a sequence of shows using yield to call the getShow function, I keep getting the first random show repeated (I am guessing because of the way closures work in F#). 现在,当我尝试使用yield来调用getShow函数来获取一系列节目时,我不断重复第一个随机节目(我猜是因为闭包在F#中的工作方式)。
let shows =
seq { for i in 1 .. 10 do yield getShow} // Keeps generating the same show over and over
What is the correct way to call the getShow function using yield so that it actually calls the function and gets a new random array? 使用yield调用getShow函数的正确方法是什么,以便它实际上调用该函数并获取新的随机数组?
getShow
is a value and not a function, so it's calculated once and you keep yielding the same value. getShow
是一个值,而不是一个函数,所以它只计算一次,你就会继续产生相同的值。 To turn it into a function you have to add ()
. 要将其转换为函数,您必须添加()
。 Also, you keep creating a new Random
instance, which is probably initialized with the same time seed, not giving you what you want. 此外,您继续创建一个新的Random
实例,该实例可能使用相同的时间种子进行初始化,而不是为您提供所需的内容。 Try this instead: 试试这个:
let random = System.Random()
let getShow() =
let doorWithCar = random.Next(3)+1
[|for door in 1..3 -> door = doorWithCar|]
let shows =
seq { for i in 1 .. 10 do yield getShow()}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.