Skip to content

Add or else methods to option closes #31 #47

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

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
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
54 changes: 45 additions & 9 deletions Source/FunicularSwitch/Option.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,13 @@ public interface IOption
public Option<T1> Bind<T1>(Func<T, Option<T1>> map) => Match(map, Option<T1>.None);

public Task<Option<T1>> Bind<T1>(Func<T, Task<Option<T1>>> bind) => Match(bind, () => Option<T1>.None);

public Option<T> OrElse(Option<T> other) => OrElse(() => other);
public Option<T> OrElse(Func<Option<T>> other) => Match(Option.Some, other);
public Task<Option<T>> OrElse(Task<Option<T>> other) => OrElse(() => other);
public Task<Option<T>> OrElse(Func<Task<Option<T>>> other) => Match(Option.Some, other);

public void Match(Action<T> some, Action? none = null)
{
Match(some.ToFunc(), none?.ToFunc<int>() ?? (() => 42));
}
public void Match(Action<T> some, Action? none = null) => Match(some.ToFunc(), none?.ToFunc<int>() ?? (() => 42));

public async Task Match(Func<T, Task> some, Func<Task>? none = null)
{
Expand All @@ -79,6 +81,16 @@ public async Task<TResult> Match<TResult>(Func<T, Task<TResult>> some, Func<Task

return await none().ConfigureAwait(false);
}

Copy link
Member

@ax0l0tl ax0l0tl Jan 31, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this actually a breaking change? -> GetValueOrDefault...

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You mean the match? In certain cases, as seen in GetValueOrDefault, it breaks the C# type inference.

public async Task<TResult> Match<TResult>(Func<T, TResult> some, Func<Task<TResult>> none)
{
if (_isSome)
{
return some(_value);
}

return await none().ConfigureAwait(false);
}

public async Task<TResult> Match<TResult>(Func<T, Task<TResult>> some, Func<TResult> none)
{
Expand All @@ -104,15 +116,15 @@ public async Task<TResult> Match<TResult>(Func<T, Task<TResult>> some, TResult n

IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();

public IEnumerator<T> GetEnumerator() => Match(v => new[] { v }, Enumerable.Empty<T>).GetEnumerator();
public IEnumerator<T> GetEnumerator() => Match(v => [v], Enumerable.Empty<T>).GetEnumerator();

public T? GetValueOrDefault() => Match(v => (T?)v, () => default);
public T? GetValueOrDefault() => Match(v => v, default(T?));

public T GetValueOrDefault(Func<T> defaultValue) => Match(v => v, defaultValue);

public T GetValueOrDefault(T defaultValue) => Match(v => v, () => defaultValue);

public T GetValueOrThrow(string? errorMessage = null) => Match(v => v, () => throw new InvalidOperationException(errorMessage ?? "Cannot access value of none option"));
public T GetValueOrThrow(string? errorMessage = null) => Match(v => v, T () => throw new InvalidOperationException(errorMessage ?? "Cannot access value of none option"));

public Option<TOther> Convert<TOther>() => Match(s => Option<TOther>.Some((TOther)(object)s!), Option<TOther>.None);

Expand Down Expand Up @@ -181,22 +193,46 @@ public static async Task<Option<TOut>> Bind<T, TOut>(this Task<Option<T>> bind,
var result = await bind.ConfigureAwait(false);
return await result.Bind(convert).ConfigureAwait(false);
}

public static async Task<Option<T>> OrElse<T>(this Task<Option<T>> option, Option<T> other)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is one I have implemented by hand in some projects as well.
Other names we had in mind were .Chain, so like you are chaining the options and take the first one that contains some, or .FallbackTo but .OrElse also sounds good

{
var result = await option.ConfigureAwait(false);
return result.OrElse(other);
}

public static async Task<Option<T>> OrElse<T>(this Task<Option<T>> option, Func<Option<T>> other)
{
var result = await option.ConfigureAwait(false);
return result.OrElse(other);
}

public static async Task<Option<T>> OrElse<T>(this Task<Option<T>> option, Task<Option<T>> other)
{
var result = await option.ConfigureAwait(false);
return await result.OrElse(other).ConfigureAwait(false);
}

public static async Task<Option<T>> OrElse<T>(this Task<Option<T>> option, Func<Task<Option<T>>> other)
{
var result = await option.ConfigureAwait(false);
return await result.OrElse(other).ConfigureAwait(false);
}

public static IEnumerable<TOut> Choose<T, TOut>(this IEnumerable<T> items, Func<T, Option<TOut>> choose) => items.SelectMany(i => choose(i));

public static Option<T> ToOption<T>(this Result<T> result) => ToOption(result, null);

public static Option<T> ToOption<T>(this Result<T> result, Action<string>? logError) =>
result.Match(
ok => Option.Some(ok),
Option.Some,
error =>
{
logError?.Invoke(error);
return Option<T>.None;
});

public static Result<T> ToResult<T>(this Option<T> option, Func<string> errorIfNone) =>
option.Match(s => Result.Ok(s), () => Result.Error<T>(errorIfNone()));
option.Match(Result.Ok, () => Result.Error<T>(errorIfNone()));

#region query-expression pattern

Expand Down
17 changes: 17 additions & 0 deletions Source/Tests/FunicularSwitch.Test/OptionSpecs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,23 @@ public void NullCoalescingWithResultBoolBehavesAsExpected()
result.Should().BeError().Subject.Should().Be("Value is missing");
}

[TestMethod]
public async Task OrElse()
{
var none = None<int>();
none.OrElse(Option<int>.None).Should().BeNone();
ShouldBeSome42(none.OrElse(42));

var some = Some(42);
ShouldBeSome42(some.OrElse(Option<int>.None));
ShouldBeSome42(some.OrElse(2));

ShouldBeSome42(await none.OrElse(() => Task.FromResult(Some(42))));
return;

void ShouldBeSome42(Option<int> option) => option.Should().BeSome().Subject.Should().Be(42);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

.BeSome() returns an AndWithConstraint<...>, so you can say

Suggested change
void ShouldBeSome42(Option<int> option) => option.Should().BeSome().Subject.Should().Be(42);
void ShouldBeSome42(Option<int> option) => option.Should().BeSome().Which.Should().Be(42);

and use .Which

}

[TestMethod]
public void QueryExpressionSelect()
{
Expand Down
Loading