隔离对象状态的共享?

ca9*_*3d9 1 f#

我的代码使用以下共享库

Module Shared
let state = new AClrClass()
let fun1 x .... = // shared function
    .... // uses state
Run Code Online (Sandbox Code Playgroud)

使用共享库的示例,state即使main在并行调用多个函数(在以下代码中)时,也由所有函数共享.

Module Caller
let f1 x = Shared.fun1 x .... // other code omitted 
let f2 x = Shared.fun1 x .... // many other functions uses the function in the Shared lib
let main () = // entry point of the module. Calls f1, f2, f3... 
Run Code Online (Sandbox Code Playgroud)

现在我需要切换到另一个Shared定义类的实现(所以每个调用Caller.main都有自己的state)

Module Shared
type Shared () =
  let state = new AClrClass()
  member __.Fun1 x .... = // shared function
    .... // uses state
Run Code Online (Sandbox Code Playgroud)

我需要更新Caller模块.可能有以下方法

  1. aClrObj将所有函数的另一个参数添加到共享库中

    Module Caller
    let f1 o x .... = o.Fun1 x .... // other code omitted 
    let f2 o x .... = o.Fun1 x .... // many other functions uses the function in the Shared lib
    let main () = // entry point of the module. Calls f1, f2, f3... 
        let aClrObj = new AClrClass()
        f1 aClrOjb x ....
    
    Run Code Online (Sandbox Code Playgroud)
  2. 定义一个可变变量并在main函数中设置它.

    Module Caller
    let mutable o = new AClrClass()
    let f1 x .... = o.Fun1 x .... // other code omitted 
    let f2 x .... = o.Fun1 x .... // many other functions uses the function in the Shared lib
    let main () = // entry point of the module. Calls f1, f2, f3... 
        o <- new AClrClass()
        let aClrObj = new AClrClass()
        f1 aClrOjb x ....
    
    Run Code Online (Sandbox Code Playgroud)

哪种方法更适合F#惯用?如何构建代码?

Aar*_*ach 5

扩展我的评论

从您的代码示例中可以准确地了解您的模块应该做什么.但是,通常,您可以通过让每个函数将状态作为其最后一个参数来管理状态,并将新状态作为其值返回.然后,您的main函数(或任何公开公开的函数)可以初始化状态并通过它调用的任何函数来管理它以执行工作,返回最终状态.

这是一个简单的例子:

type State = State of int

let add x (State state) =
    State (state + x)

let subtract x (State state) =
    State (state - x)

let multiply x (State state) =
    State (state * x)

let divide x (State state) =
    State (state / x)

let main () =
    State 0
    |> add 3
    |> multiply 4
    |> subtract 2
    |> divide 5
    // returns (State 2)
Run Code Online (Sandbox Code Playgroud)

这使用一个State对象来通过每个函数来线程化当前的执行状态.每个函数都获取当前状态并对其执行操作,返回新状态.该main函数使用其他函数执行特定的,更复杂的操作,使用管道转发操作符将当前状态穿过每个函数.