Skip to content

Commit

Permalink
feat(Seq)!: Add sequenceResultA, align sequenceResultM (#255)
Browse files Browse the repository at this point in the history
* Roll on '24

* refactor(Seq.sequenceResultM)!: Change Ok to Array

* docs: sequenceResultM

* feat(Seq): sequenceResultA

* f sequenceResultM docs

* Supress compile error

* Fix proposed version
  • Loading branch information
bartelink committed Apr 6, 2024
1 parent 08cf82b commit 4561d77
Show file tree
Hide file tree
Showing 9 changed files with 275 additions and 58 deletions.
4 changes: 4 additions & 0 deletions RELEASE_NOTES.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
### 5.0.0-alpha.1
- [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

Expand Down
4 changes: 3 additions & 1 deletion build/build.fsproj
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<IsPackable>false</IsPackable>
<!-- <NoWarn>NU1904</NoWarn>-->
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
</PropertyGroup>
<ItemGroup>
<Compile Include="DotEnv.fs" />
<Compile Include="build.fs" />
</ItemGroup>
<Import Project="..\.paket\Paket.Restore.targets" />
</Project>
</Project>
3 changes: 3 additions & 0 deletions gitbook/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@
* [sequenceResultM](list/sequenceResultM.md)
* [traverseResultA](list/traverseResultA.md)
* [sequenceResultA](list/sequenceResultA.md)
* Seqs
* [sequenceResultM](seq/sequenceResultM.md)
* [sequenceResultA](seq/sequenceResultA.md)
* Transforms
* [ofChoice](result/ofChoice.md)

Expand Down
2 changes: 1 addition & 1 deletion gitbook/list/sequenceResultA.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ let checkIfAllPrime (numbers : int list) =
numbers
|> List.map isPrime // Result<bool, string> list
|> List.sequenceResultA // Result<bool list, string list>
|> 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"]
Expand Down
69 changes: 69 additions & 0 deletions gitbook/seq/sequenceResultA.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Seq.sequenceResultA

Namespace: `FsToolkit.ErrorHandling`

## Function Signature

```fsharp
seq<Result<'a, 'b>> -> 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<int, string>
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<bool, string>
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<int> -> Result<bool, string[]>
let checkIfAllPrime (numbers: seq<int>) =
seq { for x in numbers -> isPrime x } // Result<bool, string> seq
|> Seq.sequenceResultA // Result<bool[], string[]>
|> 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
```
69 changes: 69 additions & 0 deletions gitbook/seq/sequenceResultM.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Seq.sequenceResultM

Namespace: `FsToolkit.ErrorHandling`

## Function Signature

```fsharp
seq<Result<'a, 'b>> -> Result<'a[], 'b>
```

This is monadic, stopping on the first error. Compare the example below with [sequenceResultA](sequenceResultA.md).

See also Scott Wlaschin's [Understanding traverse and sequence](https://fsharpforfunandprofit.com/posts/elevated-world-4/).

## Examples

### Example 1

```fsharp
// string -> Result<int, string>
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.sequenceResultM
// Ok [| 1; 2; 3 |]
seq { "1"; "foo"; "3"; "bar" }
|> Seq.map tryParseInt
|> Seq.sequenceResultM
// Error "unable to parse 'foo' to integer"
```

### Example 2

```fsharp
// int -> Result<bool, string>
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
// int seq -> Result<bool, string[]>
let checkIfAllPrime (numbers: seq<int>) =
numbers
|> Seq.map isPrime // seq<Result<bool, string>>
|> Seq.sequenceResultM // Result<bool[], string>
|> Result.map (Array.forall id) // shortened version of '|> Result.map (fun bools -> bools |> 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" |]
let a = seq { 2; 3; 4; 5 } |> checkIfAllPrime
// Ok false
let a = [2; 3; 5;] |> checkIfAllPrime
// Ok true
```
2 changes: 1 addition & 1 deletion src/Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<PropertyGroup>
<Description>FsToolkit.ErrorHandling is an extensive utility library based around the F# Result type, enabling consistent and powerful error handling.</Description>
<Authors>demystifyfp, TheAngryByrd</Authors>
<Copyright>Copyright © 2018-23</Copyright>
<Copyright>Copyright © 2018-24</Copyright>
<PackageProjectUrl>https://demystifyfp.gitbook.io/fstoolkit-errorhandling</PackageProjectUrl>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<PackageReadmeFile>README.md</PackageReadmeFile> <!--https://docs.microsoft.com/en-gb/nuget/reference/msbuild-targets#packagereadmefile -->
Expand Down
54 changes: 36 additions & 18 deletions src/FsToolkit.ErrorHandling/Seq.fs
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 ok
&& e.MoveNext() 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
Loading

0 comments on commit 4561d77

Please sign in to comment.