Skip to content

Commit 149cc8e

Browse files
committed
Async.bindChoice and Choice helpers
1 parent dab5fed commit 149cc8e

2 files changed

Lines changed: 36 additions & 2 deletions

File tree

src/FSharpx.Async/Async.fs

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,4 +70,26 @@ module AsyncExtensions =
7070
/// Creates an async computation which binds the result of the specified
7171
/// async computation to the specified function. The computation produced
7272
/// by the specified function is returned.
73-
static member inline bind f a = async.Bind(a, f)
73+
static member inline bind f a = async.Bind(a, f)
74+
75+
/// Maps over an async computation which produces a choice value
76+
/// using a function which maps over Choice1Of2 and itself returns a choice.
77+
/// A value of Choice2Of2 is treated like an error and passed through.
78+
static member mapChoice (f:'a -> Choice<'b, 'e>) (a:Async<Choice<'a, 'e>>) : Async<Choice<'b, 'e>> =
79+
a |> Async.map (function
80+
| Choice1Of2 a' -> f a'
81+
| Choice2Of2 e -> Choice2Of2 e)
82+
83+
/// Binds an async computation producing a choice value to another async
84+
/// computation producing a choice such that a Choice2Of2 value is passed through.
85+
static member bindChoice (f:'a -> Async<Choice<'b, 'e>>) (a:Async<Choice<'a, 'e>>) : Async<Choice<'b, 'e>> =
86+
a |> Async.bind (function
87+
| Choice1Of2 a' -> f a'
88+
| Choice2Of2 e -> Choice2Of2 e |> async.Return)
89+
90+
/// Binds an async computation producing a choice value to another async
91+
/// computation producing a choice such that a Choice2Of2 value is passed through.
92+
static member bindChoices (f:'a -> Async<Choice<'b, 'e2>>) (a:Async<Choice<'a, 'e1>>) : Async<Choice<'b, Choice<'e1, 'e2>>> =
93+
a |> Async.bind (function
94+
| Choice1Of2 a' -> f a' |> Async.map (function Choice1Of2 b -> Choice1Of2 b | Choice2Of2 e2 -> Choice2Of2 (Choice2Of2 e2))
95+
| Choice2Of2 e1 -> Choice2Of2 (Choice1Of2 e1) |> async.Return)

src/FSharpx.Async/Utils.fs

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,15 @@
11
module FSharpx.Control.Utils
22

3-
let inline konst a _ = a
3+
let inline konst a _ = a
4+
5+
module internal Choice =
6+
7+
/// Maps over the left result type.
8+
let mapl (f:'a -> 'b) = function
9+
| Choice1Of2 a -> f a |> Choice1Of2
10+
| Choice2Of2 e -> Choice2Of2 e
11+
12+
/// Maps over the right result type.
13+
let mapr (f:'b -> 'c) = function
14+
| Choice1Of2 a -> Choice1Of2 a
15+
| Choice2Of2 e -> f e |> Choice2Of2

0 commit comments

Comments
 (0)