Skip to content

Instantly share code, notes, and snippets.

@pizycki
Created October 12, 2019 17:03
Show Gist options
  • Select an option

  • Save pizycki/442878047be87bfbe8117af2d9140e6a to your computer and use it in GitHub Desktop.

Select an option

Save pizycki/442878047be87bfbe8117af2d9140e6a to your computer and use it in GitHub Desktop.
F# Combine List of Results
open Microsoft.FSharp.Collections
/// Combines collection of Results into List of Values or Errors.
/// List<Result<'a, 'b>> -> Result<List<'a>, List<'b>>
let combine (results: List<Result<'a, 'b>>): Result<List<'a>, List<'b>> =
let rec _combine (ok: List<'a>) (err: List<'b>) (res: List<Result<'a, 'b>>) =
res |> List.tryHead
|> function
| None -> (ok, err)
| Some curr ->
match curr with
| Ok x -> _combine (List.append [x] ok) err (List.tail res)
| Error e -> _combine ok (List.append [e] err) (List.tail res)
// Invoke recursive call
_combine [] [] results
|> function
| (values, []) -> Ok values
| (_, errors) -> Error errors
// All OKs
let results: List<Result<int, string>> = [ Ok 42; Ok 84 ]
let combination = combine results
printfn "%A" combination
// All Errors
let results1: List<Result<int, string>> = [ Error "Err1"; Error "Err2" ]
let combination1 = combine results1
printfn "%A" combination1
// Oks and Errors, should get Errors
let results2: List<Result<int, string>> = [ Ok 42; Ok 84; Error "Err1"; Error "Err2" ]
let combination2 = combine results2
printfn "%A" combination2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment