Thomas
Thomas

Reputation: 12107

final output of Result, in F#

This seems like a question that has an ultra simple answer, but I can't think of it:

Is there a built in method, within Result, for:

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

Upvotes: 2

Views: 420

Answers (2)

JL0PD
JL0PD

Reputation: 4498

No, there isn't any function which will allow you to do so. But you can easily define it:

[<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"

It doesn't make Result less general (as said by @brianberns), because it's not an instance member. Existence of Unwrap doesn't make Task less general

Update

After more scrupulous searching inside FSharpPlus and FSharpx.Extras I've found necessary function. It's signature ('a -> 'c) -> ('b -> 'c) -> Result<'a,'b> -> c instead of Result<'a, 'a> -> 'a and it's called Result.either in both libraries (source 1 and source 2). So in order to get value we may pass id as both parameters:

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

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

Also it's may be useful to define shortcut and call it Result.join or Result.fromEither as it's called in Haskell

Upvotes: 0

Brian Berns
Brian Berns

Reputation: 17038

No, because this function requires the Ok type and the Error type to be the same, which makes Result less general.

Upvotes: 1

Related Questions