【问题标题】:F# calling function that returns record in for loop only executes once在for循环中返回记录的F#调用函数只执行一次
【发布时间】: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的滥用。

标签: f# functional-programming


【解决方案1】:

你的getCustomer 不是一个函数,而是一个。它的主体在程序初始化期间只执行一次,结果存储在一个字段中,然后可以访问该字段。当您认为您“调用”该函数时,您实际上只是引用了该值。没有调用正在进行,因为没有什么可调用的。

要使getCustomer 成为函数,请给它一个参数。这就是函数与 F# 中的值的不同之处:如果你有一个参数,你就是一个函数;如果不是 - 你是一个价值。由于没有您想要传递给函数的实际数据,您可以给它一个unit 类型的“虚拟”(“占位符”)参数。这个类型只有一个值,那个值写成()

let createCustomer () =
    let getRand =
        let random = new System.Random()
        fun () -> random.NextDouble()

    ...

然后这样称呼它:

for i in 1 .. 10 do
    let mutable customer = createCustomer()
    printfn "i: %d\tIA: %d\tService: %d" i customer.interArrivalTime customer.serviceTime

【讨论】:

  • 那是我的问题。我最终将fun () -&gt; {...} 放在最后,而不是阻止每个循环创建System.Random()。谢谢!
  • 请注意,可以在没有显式参数的情况下声明函数,但在调用时仍需要提供至少一个参数。我认为从技术上讲,它们是包含功能的值。这在 F# 中相当常见,并且可能会让初学者感到困惑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-22
  • 1970-01-01
相关资源
最近更新 更多