gpt4 book ai didi

f# - F# 是否有异步验证库?

转载 作者:行者123 更新时间:2023-12-02 18:21:50 25 4
gpt4 key购买 nike

我在我的代码中经常使用 asyncResult 但它会在第一个错误时退出:

asyncResult {

let! a = allGood()
let! b = thisReturnsError()
let! c = neverExecuted()
}

但有时我想执行所有功能并总结错误:

validation {
let! a = doSomething()
and! b = doSomethingElse()
and! c = andAnotherThing()
}

然后我要么得到一个 Ok,要么得到一个带有错误列表的 Error。

这很好,但我希望能够同时做到这两点!

asyncValidation {
let! a = doSomethingAsync()
and! b = doSomethingElseAsync()
and! c = andAnotherThingAsync()
}

有库在做这个吗?

最佳答案

F#+您可以使用 Compose 组合应用程序:

#r @"nuget: FSharpPlus"

open FSharpPlus
open FSharpPlus.Data

// Generic applicative CE. At the moment not included in the library.
type ApplicativeBuilder<'a>() =
inherit MonadFxStrictBuilder<'a>()
member inline _.BindReturn(x, f) = map f x
let applicative<'t> = ApplicativeBuilder<'t> ()


let allGoodAsync () : Async<Validation<string, int>> = async { printfn "first success"; return Success 1 }
let thisResturnsErrorAsync () : Async<Validation<string, int>> = async { return Failure "thisReturnsError" }
let neverExecutedAsync () : Async<Validation<string, int>> = async { printfn "actually executed"; return Success 3 }

let x: Async<Validation<string, _>> =
applicative {
let! (a: int) = allGoodAsync () |> Compose
and! (b: int) = thisResturnsErrorAsync () |> Compose
and! (c: int) = neverExecutedAsync () |> Compose
return a + b + c
}
|> Compose.run
let y = Async.RunSynchronously x

结果

> 
first success
actually executed
val y: Validation<string,int> = Failure "thisReturnsError"

更新

重新审视这个答案,这可以进一步简化如下:

type ApplicativeBuilder2<'a>() =
inherit Builder<'a>()
member inline _.BindReturn(x, f) = map f x
member inline _.Source x = Compose x
member inline _.Run x = Compose.run x
let applicative2<'t> = ApplicativeBuilder2<'t> ()

所以你不需要搞乱 Compose :

let x: Async<Validation<string, _>> =
applicative2 {
let! (a: int) = allGoodAsync ()
and! (b: int) = thisResturnsErrorAsync ()
and! (c: int) = neverExecutedAsync ()
return a + b + c
}

并且由于评论中提到的 F# 类型推断错误仍未修复,我现在可以说 applicativeapplicative2 肯定会包含在下一版本的F#+。

关于f# - F# 是否有异步验证库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70777567/

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