-
Notifications
You must be signed in to change notification settings - Fork 62
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor(Seq.sequenceResultM)!: Change Ok to Array
Showing
3 changed files
with
63 additions
and
62 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,19 +1,37 @@ | ||
namespace FsToolkit.ErrorHandling | ||
|
||
[<RequireQualifiedAccess>] | ||
module Seq = | ||
|
||
let sequenceResultM (xs: seq<Result<'t, 'e>>) : Result<'t seq, 'e> = | ||
let rec loop xs ts = | ||
match Seq.tryHead xs with | ||
| Some x -> | ||
x | ||
|> Result.bind (fun t -> loop (Seq.tail xs) (t :: ts)) | ||
| None -> | ||
Ok( | ||
List.rev ts | ||
|> List.toSeq | ||
) | ||
|
||
// Seq.cache prevents double evaluation in Seq.tail | ||
loop (Seq.cache xs) [] | ||
module FsToolkit.ErrorHandling.Seq | ||
|
||
let sequenceResultM (xs: seq<Result<'t, 'e>>) : Result<'t[], 'e> = | ||
if isNull xs then | ||
nullArg (nameof xs) | ||
|
||
let acc = ResizeArray() | ||
let mutable err = Unchecked.defaultof<_> | ||
let mutable ok = true | ||
use e = xs.GetEnumerator() | ||
|
||
while e.MoveNext() | ||
&& ok do | ||
match e.Current with | ||
| Ok r -> acc.Add r | ||
| Error e -> | ||
ok <- false | ||
err <- e | ||
|
||
if ok then Ok(acc.ToArray()) else Error err | ||
|
||
let sequenceResultA (xs: seq<Result<'t, 'e>>) : Result<'t[], 'e[]> = | ||
if isNull xs then | ||
nullArg (nameof xs) | ||
|
||
let oks = ResizeArray() | ||
let errs = ResizeArray() | ||
|
||
for x in xs do | ||
match x with | ||
| Ok r -> oks.Add r | ||
| Error e -> errs.Add e | ||
|
||
match errs.ToArray() with | ||
| [||] -> Ok(oks.ToArray()) | ||
| errs -> Error errs |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters