gpt4 book ai didi

f# - 如何避免在 F# 中更改状态?

转载 作者:行者123 更新时间:2023-12-01 12:30:25 25 4
gpt4 key购买 nike

我有一个使用 F# 库的 C# WebAPI 应用程序。

F# 库有一个值:

 let mutable CurrentCustomer:Customer option = None

我还有:

 let Customers:Map<string,Customer> option = None

CustomersCustomer 都是“全局变量”。在启动时,C# 应用程序将一组客户加载到这个全局变量 Customers 中。然后我有一个 customersController,它有一个 Post,它调用一个 F# 函数 setCurrentCustomer 来设置全局变量 CurrentCustomer来自存储在 Customers 中的集合:

 // Post in customersController:

public HttpResponseMessage Post(string identifier)
{
var _customer = FSharpLibrary.setCurrentCustomer(identifier);
// code
}

// setCurrentCustomer function:

let mutable CurrentCustomer:Customer option = None
let setCurrentCustomer() =
CurrentCustomer <- customer |> Some
CurrentCustomer

是否有任何方法可以通过更改 CurrentCustomer 来避免更改状态?

我知道我可以创建一个函数,它接受一个 CurrentCustomer 对象并返回一个新的 CurrentCustomer 对象,但是 customersController 怎么知道当前客户设置为?

有什么方法可以避免使用这个全局可变变量Customer

最佳答案

Is there any way to avoid changing state by changing CurrentCustomer?

是的,有很多方法可以做到这一点,但大多数方法都涉及更改 FSharpLibrary 的设计,使其不依赖于可变状态。

作为一个完全笼统的答案,您可以应用 State Monad,但涉及较少的东西通常就足够了。但是,如果您不知道您正在尝试完成什么,则无法准确回答。

how will the customersController know what is the current customer set to?

它已经知道了,因为它将当前客户设置为 Post 方法中的 identifier 参数。该值在整个方法的范围内。

问题是为什么您的 FSharpLibrary 具有可变状态?你不能用纯函数来实现它吗?

关于f# - 如何避免在 F# 中更改状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34610442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com