gpt4 book ai didi

asynchronous - 异步不可知的高阶函数

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

假设我们有一个提供高阶函数的库 applyTest .

这可以与异步函数一起使用吗asyncFunction同时保留异步代码的好处?

是否可以将库设计为更好地支持异步应用程序,而无需专门提供异步版本?

let applyTest f =
f 2 > 0

let syncFunction x =
x - 1

let asyncFunction x =
x - 2 |> async.Return

async {
let a = applyTest syncFunction
let b = applyTest (asyncFunction >> Async.RunSynchronously)
printfn "a = %b, b = %b" a b
}
|> Async.RunSynchronously

最佳答案

如果您不想丢失强类型检查或像示例中那样同步运行异步计算,则需要提供单独的异步版本。这两种情况都应该尽量避免。

如果您想避免重复实际测试部分( f 2 > 0 ),您可以将其拆分为一个传递参数 2 的函数。到函数和检查值是否大于零的函数:

// LIBRARY CODE

let checkValue x = x > 0

// This function is generic so it can return a value or an async value
// (int -> 'a) -> 'a
let runTestFunction f = f 2

// (int -> int) -> bool
let applyTest f = f |> runTestFunction |> checkValue

// (int -> Async<int>) -> Async<bool>
let applyTestAsync f = async {
let! value = runTestFunction f // use let! to await the value
return checkValue value }

// USAGE

let syncFunction x = x - 1
let asyncFunction x = x - 2 |> async.Return

async {
let a = applyTest syncFunction
let! b = applyTestAsync asyncFunction // use let! to await the test result
printfn "a = %b, b = %b" a b
}

另一种选择是使用重载方法。这建立在上面定义的函数之上:
type Test =
static member Apply f = applyTest f
static member Apply f = applyTestAsync f

// USAGE

async {
let a = Test.Apply syncFunction
let! b = Test.Apply asyncFunction // We still need to consume this differently with a let!
printfn "a = %b, b = %b" a b
}

关于asynchronous - 异步不可知的高阶函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57353094/

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