Skip to content

Commit 8d0e534

Browse files
authored
Add Obj module (#663)
1 parent 003518c commit 8d0e534

2 files changed

Lines changed: 37 additions & 0 deletions

File tree

src/FSharpPlus/Extensions/Obj.fs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
namespace FSharpPlus
2+
3+
/// Additional operations on (reference) objects
4+
[<RequireQualifiedAccess>]
5+
module Obj =
6+
7+
/// <summary>Returns the source if it is not null; otherwise, returns the specified default value.</summary>
8+
/// <param name="value">The default value to return if the source is null.</param>
9+
/// <param name="source">The source object.</param>
10+
/// <returns>The source if it is not null; otherwise, the specified default value.</returns>
11+
/// <remarks>The default value is evaluated eagerly.</remarks>
12+
let defaultValue value (source: 'T) : 'T =
13+
match source with
14+
| null -> value
15+
| value -> value
16+
17+
/// <summary>Returns the source if it is not null; otherwise, invokes the specified function to obtain a default value.</summary>
18+
/// <param name="fNull">The function to invoke to obtain a default value if the source is null.</param>
19+
/// <param name="source">The source object.</param>
20+
/// <returns>The source if it is not null; otherwise, the result of invoking the specified function.</returns>
21+
/// <remarks>The fNull function is only invoked if the source is null.</remarks>
22+
let inline defaultWith ([<InlineIfLambda>]fNull: unit -> 'T) (source: 'T) : 'T =
23+
match source with
24+
| null -> fNull ()
25+
| value -> value
26+
27+
/// <summary>Applies one of two functions to the source object based on whether it is null or not.</summary>
28+
/// <param name="fValue">The function to apply if the source is not null.</param>
29+
/// <param name="fNull">The function to apply if the source is null.</param>
30+
/// <param name="source">The source object.</param>
31+
/// <returns>The result of applying fValue to the source if it is not null; otherwise, the result of applying fNull.</returns>
32+
/// <remarks>Only one of the functions is invoked based on the nullity of the source.</remarks>
33+
let inline either ([<InlineIfLambda>]fValue: 'T -> 'U) ([<InlineIfLambda>]fNull: unit -> 'U) (source: 'T) : 'U =
34+
match source with
35+
| null -> fNull ()
36+
| value -> fValue value

src/FSharpPlus/FSharpPlus.fsproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
<Compile Include="Internals.fs" />
3535
<Compile Include="Extensions/Option.fs" />
3636
<Compile Include="Extensions/ValueOption.fs" />
37+
<Compile Include="Extensions/Obj.fs" />
3738
<Compile Include="Extensions/Nullable.fs" />
3839
<Compile Include="Extensions/Result.fs" />
3940
<Compile Include="Extensions/Choice.fs" />

0 commit comments

Comments
 (0)