在模块中相互调用功能

时间:2016-09-22 18:06:02

标签: f#

module Sample

let foo() = 
   do-something-general

let a() =
   foo()
   // another actions

let b() =
   foo()
   // another actions

let c() =
   foo()
   // another actions

我有一个包含这组功能的模块。每个函数都有一些工作,但在它们调用foo()函数之前。

有没有办法避免在每个函数中编写foo()

更新:抱歉,我有一个错误,现在已经改变了问题

2 个答案:

答案 0 :(得分:1)

您可以传递do_something_general()作为功能签名的一部分:

let a do_something = 
    do_something()
    //other acitons

将其称为

a do_something_general

您还可以考虑使用以下内容尝试计算工作流程:

type FooBuilder() =
    let foo () = printfn "This is the doing general stuff"

    member this.Bind(x, f) = 
        foo ()
        f x

    member this.Return(x) = 
        x

let foo = new FooBuilder()

let a() = 
    foo
        {
        let! x= (fun () -> printfn "This happens after the general stuff")
        return x()
        }

然后调用a会导致:

> a();;
This is the doing general stuff
This happens after the general stuff
val it : unit = ()

答案 1 :(得分:0)

另一种选择是定义一个简单的包装函数:

let wrap f () = 
    foo ()
    f ()

然后你可以定义你想要的功能

let a () = printfn "stuff"
let b () = printfn "more stuff"

然后将它们换成所需的效果:

let wrappedA = wrap a
let wrappedB = wrap b