Skip to content

Commit 04e4c38

Browse files
ratsclubMarcos Benevides
andauthored
Added bind operator for Option (#210)
Co-authored-by: Marcos Benevides <[email protected]>
1 parent d876753 commit 04e4c38

File tree

3 files changed

+34
-0
lines changed

3 files changed

+34
-0
lines changed

src/FsToolkit.ErrorHandling/FsToolkit.ErrorHandling.fsproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
<Compile Include="ValidationCE.fs" />
2929
<Compile Include="Option.fs" />
3030
<Compile Include="OptionCE.fs" />
31+
<Compile Include="OptionOp.fs" />
3132
<Compile Include="ValueOption.fs" />
3233
<Compile Include="ValueOptionCE.fs" />
3334
<Compile Include="AsyncOption.fs" />
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
namespace FsToolkit.ErrorHandling.Operator.Option
2+
3+
open FsToolkit.ErrorHandling
4+
5+
[<AutoOpen>]
6+
module Option =
7+
let inline (>>=)
8+
(input: Option<'input>)
9+
([<InlineIfLambda>] binder: 'input -> Option<'output>)
10+
: Option<'output> =
11+
Option.bind binder input

tests/FsToolkit.ErrorHandling.Tests/Option.fs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ open SampleDomain
1010
open TestData
1111
open TestHelpers
1212
open FsToolkit.ErrorHandling
13+
open FsToolkit.ErrorHandling.Operator.Option
1314

1415

1516
let traverseResultTests =
@@ -172,6 +173,26 @@ let ofPairTests =
172173
Expect.equal (Option.ofPair pair) (None) ""
173174
]
174175

176+
let optionOperatorsTests =
177+
testList "Option Operators Tests" [
178+
testCase "bind operator"
179+
<| fun _ ->
180+
let evenInt x = if x % 2 = 0 then Some x else None
181+
182+
let tryParseInt (x: string) =
183+
match Int32.TryParse x with
184+
| true, value -> Some value
185+
| _ -> None
186+
187+
let tryParseEvenInt str =
188+
tryParseInt str
189+
>>= evenInt
190+
191+
192+
tryParseEvenInt "2"
193+
|> Expect.hasSomeValue 2
194+
]
195+
175196
let allTests =
176197
testList "Option Tests" [
177198
traverseResultTests
@@ -182,4 +203,5 @@ let allTests =
182203
bindNullTests
183204
eitherTests
184205
ofPairTests
206+
optionOperatorsTests
185207
]

0 commit comments

Comments
 (0)