Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added bind operator for Option #210

Merged
merged 1 commit into from
Feb 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/FsToolkit.ErrorHandling/FsToolkit.ErrorHandling.fsproj
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
<Compile Include="ValidationCE.fs" />
<Compile Include="Option.fs" />
<Compile Include="OptionCE.fs" />
<Compile Include="OptionOp.fs" />
<Compile Include="ValueOption.fs" />
<Compile Include="ValueOptionCE.fs" />
<Compile Include="AsyncOption.fs" />
Expand Down
11 changes: 11 additions & 0 deletions src/FsToolkit.ErrorHandling/OptionOp.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace FsToolkit.ErrorHandling.Operator.Option

open FsToolkit.ErrorHandling

[<AutoOpen>]
module Option =
let inline (>>=)
(input: Option<'input>)
([<InlineIfLambda>] binder: 'input -> Option<'output>)
: Option<'output> =
Option.bind binder input
22 changes: 22 additions & 0 deletions tests/FsToolkit.ErrorHandling.Tests/Option.fs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ open SampleDomain
open TestData
open TestHelpers
open FsToolkit.ErrorHandling
open FsToolkit.ErrorHandling.Operator.Option


let traverseResultTests =
Expand Down Expand Up @@ -172,6 +173,26 @@ let ofPairTests =
Expect.equal (Option.ofPair pair) (None) ""
]

let optionOperatorsTests =
testList "Option Operators Tests" [
testCase "bind operator"
<| fun _ ->
let evenInt x = if x % 2 = 0 then Some x else None

let tryParseInt (x: string) =
match Int32.TryParse x with
| true, value -> Some value
| _ -> None

let tryParseEvenInt str =
tryParseInt str
>>= evenInt


tryParseEvenInt "2"
|> Expect.hasSomeValue 2
]

let allTests =
testList "Option Tests" [
traverseResultTests
Expand All @@ -182,4 +203,5 @@ let allTests =
bindNullTests
eitherTests
ofPairTests
optionOperatorsTests
]