gpt4 book ai didi

dependency-injection - 将函数注入(inject)计算表达式

转载 作者:行者123 更新时间:2023-12-01 10:41:48 24 4
gpt4 key购买 nike

以下代码示例来自 Scott Wlaschin 的网站 F# for fun and profit.

type LoggingBuilder() =
let log p = printfn "expression is %A" p

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

member this.Return(x) =
x

let logger = new LoggingBuilder()

let loggedWorkflow =
logger
{
let! x = 42
let! y = 43
let! z = x + y
return z
}

有没有办法将函数而不是 printfn 注入(inject)到 LoggingBuilder() 中?

最佳答案

您可以只向构建器类型添加一个参数:

type LoggingBuilder(lf: obj -> unit) =
let log p = lf p

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

member this.Return(x) =
x

let logger = new LoggingBuilder(printfn "expression is %A")

如果您想使输入类型比 obj 更具体,则可以使构建器通用

type LoggingBuilder<'a>(lf: 'a -> unit) =
...

let logger = new LoggingBuilder<int>(printfn "Got %i")

关于dependency-injection - 将函数注入(inject)计算表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29635045/

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