结果的最终输出,在 F# 中

final output of Result, in F#

这个问题好像是一个超级简单的答案,但我想不出来:

Result 中是否有内置方法用于:

let (a: Result<'a, 'a>) = ...
match a with
| Ok x    -> x
| Error e -> e

不能,因为这个函数要求Ok类型和Error类型相同,这使得Result不太通用。

不,没有任何功能可以让您这样做。但是你可以很容易地定义它:

[<RequireQualifiedAccess>]
module Result =
    let join (value: Result<'a, 'a>) =
         match value with
         | Ok v -> v
         | Error e -> e

let getResult s =
    if System.String.IsNullOrEmpty s then
        Error s
    else 
        Ok s

let a =
   getResult "asd"
   |> Result.join
   |> printfn "%s"

它不会使 Result 不那么通用(如@brianberns 所说),因为它不是实例成员。 Unwrap 的存在并不会使 Task 不那么普遍

更新

在 FSharpPlus 和 FSharpx.Extras 中仔细搜索后,我发现了必要的功能。它的签名是 ('a -> 'c) -> ('b -> 'c) -> Result<'a,'b> -> c 而不是 Result<'a, 'a> -> 'a,并且在两个库 (source 1 and source 2) 中都称为 Result.either。因此,为了获得价值,我们可以将 id 作为两个参数传递:

#r "nuget:FSharpPlus"
open FSharpPlus
// OR
#r "nuget:FSharpx.Extras"
open FSharpx

getResult "asd"
|> Result.either id id
|> printfn "%s"

此外,定义快捷方式并将其命名为 Result.joinResult.fromEither 可能会有用,因为它在 Haskell

中是 called