简体   繁体   English

F#MailboxProcessor和功能设计

[英]F# MailboxProcessor and Functional Design

If state is regarded as a bad idea for functions why is it regarded as okay have a state when you use a MailboxProcessor? 如果状态被认为是函数的坏主意,为什么当你使用MailboxProcessor时它被视为没有状态?

To expand, I was explaining functional programming to someone, how functions don't use state (no variables outside the function - ie same data out for same data in) and the good things that this brings. 为了扩展,我向某人解释函数式编程,函数如何不使用状态(函数外没有变量 - 即相同数据的相同数据)以及它带来的好处。 But then I got thinking about MailboxProcessor and the way it uses recursion to persist state between function calls, and I can't quite reconcile why it's okay in that situation. 但后来我开始考虑使用MailboxProcessor以及它使用递归来在函数调用之间保持状态的方式,而且我不能完全调和为什么在这种情况下它是可以的。

Is it a case of it being the least bad way of persisting state? 这是持久状态最不好的方式吗?

The evil really is shared mutable state . 邪恶真的是共享的可变状态 In single-threaded case, shared mutable state means that functions cannot be safely composed - because one call can modify some state which is then read by a second call and so you'll get unexpected results. 在单线程情况下,共享可变状态意味着函数无法安全组合 - 因为一个调用可以修改某个状态,然后由第二个调用读取,因此您将获得意外结果。 In multi-threaded case, shared mutable state means that you have potential for race conditions. 在多线程情况下,共享可变状态意味着您有可能出现竞争条件。

Functional programming generally avoids mutation. 功能编程通常避免突变。 Functions can still share some state (eg closure can capture a state), but it cannot be mutated. 函数仍然可以共享一些状态(例如,闭包可以捕获一个状态),但它不能被变异。 In single-threaded case, there is also no non-determinism. 在单线程情况下,也没有非确定性。 In multi-threaded case, pretty much the only thing that you can do in pure functional style is to do fork-join parallelism (and data-parallelism) which does not need mutable state and is fully deterministic. 在多线程的情况下,在纯函数风格中你唯一可以做的就是做fork-join并行(和数据并行),它不需要可变状态并且是完全确定的。

Agent-based programming also avoids shared mutable state, but in a different way. 基于代理的编程也避免了共享的可变状态,但是以不同的方式。 You have isolated agents that can only share immutable messages. 您有隔离的代理只能共享不可变的消息。 So there is some non-determinism (because they communicate by sending messages), but they only exchange immutable values. 因此存在一些非确定性(因为它们通过发送消息进行通信),但它们只交换不可变的值。 In fact, you can even use mutable state inside an agent - as long as it is not shared, you still avoid shared mutable state. 实际上,您甚至可以在代理中使用可变状态 - 只要它不共享,您仍然可以避免共享可变状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM