【发布时间】:2017-05-28 01:00:25
【问题描述】:
我主要使用 C# 工作,并且是 F#/函数语言的新手,但我遇到了一个非常简单的程序的问题。
我有一个函数可以创建一个包含两个整数字段的记录。这些字段在match 内选择System.Random.NextDouble 以与某些概率对齐。然后我有一个 for 循环应该运行 createCustomer 函数四次。
我遇到的问题是 Customer 对于 for 循环的所有 10 次迭代都是相同的,而 getIATime 内部的 printfn 似乎只执行一次。
程序.fs
open Simulation
[<EntryPoint>]
let main argv =
printfn "%A" argv
printfn "Test"
for i in 1 .. 10 do
let mutable customer = createCustomer
printfn "i: %d\tIA: %d\tService: %d" i customer.interArrivalTime customer.serviceTime
ignore (System.Console.ReadLine()) //Wait for keypress @ the end
0 // return an integer exit code
Simulation.fs
module Simulation
type Customer = {
interArrivalTime: int
serviceTime: int
}
let createCustomer =
let getRand =
let random = new System.Random()
fun () -> random.NextDouble()
let getIATime rand =
printf "Random was: %f\n" rand
match rand with
| rand when rand <= 0.09 -> 0
| rand when rand <= 0.26 -> 1
| rand when rand <= 0.53 -> 2
| rand when rand <= 0.73 -> 3
| rand when rand <= 0.88 -> 4
| rand when rand <= 1.0 -> 5
let getServiceTime rand =
match rand with
| rand when rand <= 0.2 -> 1
| rand when rand <= 0.6 -> 2
| rand when rand <= 0.88 -> 3
| rand when rand <= 1.0 -> 4
{interArrivalTime = getIATime (getRand()); serviceTime = getServiceTime (getRand())}
【问题讨论】:
-
循环中不需要那个“可变”关键字。在这种情况下,它与 C# 相同。如果您要在 C# 中的循环内声明一个变量,它就不是同一个变量,而是循环的每次迭代的一个新变量。
-
好电话,忘了我什至把那个放在里面了。我曾尝试添加它以查看它是否可以解决我遇到的问题
-
如果你要做代码审查,还有
match的滥用。