From b254b92c471a80a7e8c273105e64fd6477a434bb Mon Sep 17 00:00:00 2001 From: Ruben Bartelink Date: Thu, 15 Feb 2024 01:27:44 +0000 Subject: [PATCH] feat(Seq): sequenceResultA --- RELEASE_NOTES.md | 1 + gitbook/SUMMARY.md | 1 + gitbook/list/sequenceResultA.md | 2 +- gitbook/seq/sequenceResultA.md | 69 ++++++++++++++++++++++ src/FsToolkit.ErrorHandling/Seq.fs | 16 +++++ tests/FsToolkit.ErrorHandling.Tests/Seq.fs | 66 ++++++++++++++++++++- 6 files changed, 153 insertions(+), 2 deletions(-) create mode 100644 gitbook/seq/sequenceResultA.md diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 62cdc913..1dc56cce 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -1,5 +1,6 @@ ### 4.16.0 - [refactor!: Seq.sequenceResultM returns Array instead of seq](https://github.com/demystifyfp/FsToolkit.ErrorHandling/pull/255) [@bartelink](https://github.com/bartelink) +- [feat(Seq): sequenceResultA](https://github.com/demystifyfp/FsToolkit.ErrorHandling/pull/255) [@bartelink](https://github.com/bartelink) ### 4.15.1 - January 15, 2024 - [Doc updates](https://github.com/demystifyfp/FsToolkit.ErrorHandling/pull/247) Credits @1eyewonder diff --git a/gitbook/SUMMARY.md b/gitbook/SUMMARY.md index af5244eb..3aacc637 100644 --- a/gitbook/SUMMARY.md +++ b/gitbook/SUMMARY.md @@ -27,6 +27,7 @@ * [sequenceResultA](list/sequenceResultA.md) * Seqs * [sequenceResultM](seq/sequenceResultM.md) + * [sequenceResultA](seq/sequenceResultA.md) * Transforms * [ofChoice](result/ofChoice.md) diff --git a/gitbook/list/sequenceResultA.md b/gitbook/list/sequenceResultA.md index a2e0dacc..113194f8 100644 --- a/gitbook/list/sequenceResultA.md +++ b/gitbook/list/sequenceResultA.md @@ -59,7 +59,7 @@ let checkIfAllPrime (numbers : int list) = numbers |> List.map isPrime // Result list |> List.sequenceResultA // Result - |> Result.map (List.forall id) // shortened version of '|> Result.map (fun boolList -> boolList |> List.map (fun x -> x = true))' + |> Result.map (List.forall id) // shortened version of '|> Result.map (fun boolList -> boolList |> List.forAll (fun x -> x = true)) let a = [1; 2; 3; 4; 5;] |> checkIfAllPrime // Error ["1 must be greater than 1"] diff --git a/gitbook/seq/sequenceResultA.md b/gitbook/seq/sequenceResultA.md new file mode 100644 index 00000000..60b6761b --- /dev/null +++ b/gitbook/seq/sequenceResultA.md @@ -0,0 +1,69 @@ +# Seq.sequenceResultA + +Namespace: `FsToolkit.ErrorHandling` + +## Function Signature + +```fsharp +seq> -> Result<'a[], 'b[]> +``` + +This is applicative, collecting all errors. Compare the example below with [sequenceResultM](sequenceResultM.md). + +See also Scott Wlaschin's [Understanding traverse and sequence](https://fsharpforfunandprofit.com/posts/elevated-world-4/). + +## Examples + +### Example 1 + +```fsharp +// string -> Result +let tryParseInt str = + match Int32.TryParse str with + | true, x -> Ok x + | false, _ -> Error $"unable to parse '{str}' to integer" + +["1"; "2"; "3"] +|> Seq.map tryParseInt +|> Seq.sequenceResultA +// Ok [| 1; 2; 3 |] + +["1"; "foo"; "3"; "bar"] +|> Seq.map tryParseInt +|> Seq.sequenceResultA +// Error [| "unable to parse 'foo' to integer" +// "unable to parse 'bar' to integer" |] +``` + +### Example 2 + +```fsharp +// int -> Result +let isPrime (x: int) = + if x < 2 then Error $"{x} must be greater than 1" + elif x = 2 then Ok true + else + let rec isPrime' (x : int) (i : int) = + if i * i > x then Ok true + elif x % i = 0 then Ok false + else isPrime' x (i + 1) + isPrime' x 2 + +// seq -> Result +let checkIfAllPrime (numbers: seq) = + seq { for x in numbers -> isPrime x } // Result seq + |> Seq.sequenceResultA // Result + |> Result.map (Seq.forall id) // shortened version of '|> Result.map (fun results -> results |> Array.forall (fun x -> x = true))' + +let a = [| 1; 2; 3; 4; 5 |] |> checkIfAllPrime +// Error [| "1 must be greater than 1" |] + +let b = [ 1; 2; 3; 4; 5; 0 ] |> checkIfAllPrime +// Error [| "1 must be greater than 1"; "0 must be greater than 1" |] + +let a = seq { 2; 3; 4; 5 } |> checkIfAllPrime +// Ok false + +let a = seq { 2; 3; 5 } |> checkIfAllPrime +// Ok true +``` diff --git a/src/FsToolkit.ErrorHandling/Seq.fs b/src/FsToolkit.ErrorHandling/Seq.fs index 281a2ba1..da3ad5ae 100644 --- a/src/FsToolkit.ErrorHandling/Seq.fs +++ b/src/FsToolkit.ErrorHandling/Seq.fs @@ -19,3 +19,19 @@ let sequenceResultM (xs: seq>) : Result<'t[], 'e> = err <- e if ok then Ok(acc.ToArray()) else Error err + +let sequenceResultA (xs: seq>) : 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 diff --git a/tests/FsToolkit.ErrorHandling.Tests/Seq.fs b/tests/FsToolkit.ErrorHandling.Tests/Seq.fs index 908d138d..c6d88f2f 100644 --- a/tests/FsToolkit.ErrorHandling.Tests/Seq.fs +++ b/tests/FsToolkit.ErrorHandling.Tests/Seq.fs @@ -79,4 +79,68 @@ let sequenceResultMTests = Expect.equal counter 0 "evaluation of the sequence stops at the first error" ] -let allTests = testList "Seq Tests" [ sequenceResultMTests ] +let sequenceResultATests = + testList "Seq.sequenceResultA Tests" [ + testCase "valid data only" + <| fun _ -> + let tweets = + seq { + "Hi" + "Hello" + "Hola" + } + + let expected = Ok [| for t in tweets -> tweet t |] + + let actual = Seq.sequenceResultA (Seq.map Tweet.TryCreate tweets) + + Expect.equal actual expected "Should yield an array of valid tweets" + + testCase "valid and multiple invalid data" + <| fun _ -> + let tweets = [ + "" + "Hello" + aLongerInvalidTweet + ] + + let expected = + Error [| + emptyTweetErrMsg + longerTweetErrMsg + |] + + let actual = Seq.sequenceResultA (Seq.map Tweet.TryCreate tweets) + + Expect.equal actual expected "traverse the seq and return all the errors" + + testCase "iterates exacly once" + <| fun _ -> + let mutable counter = 0 + + let tweets = + seq { + "Hi" + "Hello" + "Hola" + aLongerInvalidTweet + + counter <- + counter + + 1 + } + + let expected = Error [| longerTweetErrMsg |] + + let actual = Seq.sequenceResultA (Seq.map Tweet.TryCreate tweets) + + Expect.equal actual expected "traverse the seq and return all the errors" + + Expect.equal counter 1 "evaluation of the sequence completes exactly once" + ] + +let allTests = + testList "Seq Tests" [ + sequenceResultMTests + sequenceResultATests + ]