Skip to content

Added convenience methods for easier Monad creation and Monad chaining #258

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

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from
Open
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
89 changes: 89 additions & 0 deletions src/DotNext/Optional.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,69 @@ public static class Optional
public static async Task<Optional<TOutput>> Convert<TInput, TOutput>(this Task<Optional<TInput>> task, Converter<TInput, TOutput> converter)
=> (await task.ConfigureAwait(false)).Convert(converter);

/// <summary>
/// If a value is present, apply the provided mapping function to it, and if the result is
/// non-null, return an Optional describing the result. Otherwise returns <see cref="Optional{T}.None"/>.
/// </summary>
/// <typeparam name="TInput">The type of stored in the Optional container.</typeparam>
/// <typeparam name="TOutput">The type of the result of the mapping function.</typeparam>
/// <param name="task">The task containing Optional value.</param>
/// <param name="converter">A mapping function to be applied to the value, if present.</param>
/// <returns>An Optional describing the result of applying a mapping function to the value of this Optional, if a value is present, otherwise <see cref="Optional{T}.None"/>.</returns>
public static async Task<Optional<TOutput>> Convert<TInput, TOutput>(this Task<Optional<TInput>> task, Converter<TInput, Optional<TOutput>> converter)
=> (await task.ConfigureAwait(false)).Convert(converter);

/// <summary>
/// If a value is present, apply the provided mapping function to it, and if the result is
/// non-null, return an Optional describing the result. Otherwise returns <see cref="Optional{T}.None"/>.
/// </summary>
/// <typeparam name="TInput">The type of stored in the Optional container.</typeparam>
/// <typeparam name="TOutput">The type of the result of the mapping function.</typeparam>
/// <param name="task">The task containing Optional value.</param>
/// <param name="converter">A mapping function to be applied to the value, if present.</param>
/// <returns>An Optional describing the result of applying a mapping function to the value of this Optional, if a value is present, otherwise <see cref="Optional{T}.None"/>.</returns>
public static async Task<Optional<TOutput>> Convert<TInput, TOutput>(this Task<Optional<TInput>> task, Converter<TInput, Task<Optional<TOutput>>> converter)
Copy link
Collaborator

Choose a reason for hiding this comment

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

This method is also redundant, because Convert is already defined for generic Task<T> in DotNext.Threading.Tasks.Conversion static class.

Copy link
Author

@julianthurner julianthurner Feb 25, 2025

Choose a reason for hiding this comment

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

Sorry it took me a while to find time again, I think this method is not completely redundant because omitting it means having to handle the Optional yourself every time instead of being able to rely on the monad chain handling it which defeats the whole purpose of the chain (see examples below). It also means that if I use static conversion methods which I might re-use elsewhere in the code instead of lambdas, I have to force Optional<TInput> as input type instead of being able to simply accept TInput.

Without extension method:

var optional = await Task.FromResult(Optional.FromValue(42))
    .Convert(async x => x > 10 ? x * 2.0 - 20 : Optional<double>.None)
    .Convert(async x => x > 0 ? "Success" : Optional<string>.None);

With extension method:

var optional = await Task.FromResult(Optional.From(42))
    .Convert(async x => x.HasValue && x.Value > 10 ? x.Value * 2.0 - 20 : Optional<double>.None)
    .Convert(async x => x.HasValue && x.Value > 0 ? "Success" : Optional<string>.None);

Copy link
Collaborator

Choose a reason for hiding this comment

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

The proposed method has no cancellation token support. Since 5.19.0 that is just released, there is Convert with it:

Task<Optional<TOutput>> Convert<TInput, TOutput>(this Task<Optional<TInput>> task,
        Func<TInput, CancellationToken, Task<TOutput>> converter, CancellationToken token = default)

=> await (await task.ConfigureAwait(false)).Convert(converter).ConfigureAwait(false);

/// <summary>
/// Creates <see cref="Result{T}"/> from <see cref="Optional{T}"/> instance.
/// </summary>
/// <param name="optional">The optional value.</param>
/// <returns>The converted optional value.</returns>
public static Result<T> ToResult<T>(this in Optional<T> optional)
=> Result<T>.FromOptional(optional);

/// <summary>
/// Creates <see cref="Result{T}"/> from <see cref="Optional{T}"/> instance.
/// </summary>
/// <param name="task">The task containing Optional value.</param>
/// <returns>The converted optional value.</returns>
public static async Task<Result<T>> ToResult<T>(this Task<Optional<T>> task)
=> Result<T>.FromOptional(await task.ConfigureAwait(false));

/// <summary>
/// Creates <see cref="Result{T, TError}"/> from <see cref="Optional{T}"/> instance.
/// </summary>
/// <param name="optional">The optional value.</param>
/// <param name="error">The error code to apply if the value is not present.</param>
/// <returns>The converted optional value.</returns>
public static Result<T, TError> ToResult<T, TError>(this in Optional<T> optional, TError error)
where TError : struct, Enum
=> optional.HasValue ? new(optional.Value) : new(error);

/// <summary>
/// Creates <see cref="Result{T, TError}"/> from <see cref="Optional{T}"/> instance.
/// </summary>
/// <param name="task">The task containing Optional value.</param>
/// <param name="error">The error code to apply if the value is not present.</param>
/// <returns>The converted optional value.</returns>
public static async Task<Result<T, TError>> ToResult<T, TError>(this Task<Optional<T>> task, TError error)
where TError : struct, Enum
{
var optional = await task.ConfigureAwait(false);
return optional.HasValue ? new(optional.Value) : new(error);
}

/// <summary>
/// If a value is present, returns the value, otherwise throw exception.
/// </summary>
Expand Down Expand Up @@ -553,6 +616,11 @@ private Optional<TResult> ConvertOptional<TResult, TConverter>(TConverter conver
where TConverter : struct, ISupplier<T, Optional<TResult>>
=> HasValue ? converter.Invoke(value) : Optional<TResult>.None;

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private Task<Optional<TResult>> ConvertOptionalTask<TResult, TConverter>(TConverter converter)
where TConverter : struct, ISupplier<T, Task<Optional<TResult>>>
=> HasValue ? converter.Invoke(value) : Task.FromResult(Optional<TResult>.None);

/// <summary>
/// If a value is present, apply the provided mapping function to it, and if the result is
/// non-null, return an Optional describing the result. Otherwise, returns <see cref="None"/>.
Expand All @@ -570,10 +638,31 @@ public Optional<TResult> Convert<TResult>(Converter<T, Optional<TResult>> mapper
/// <typeparam name="TResult">The type of the result of the mapping function.</typeparam>
/// <param name="mapper">A mapping function to be applied to the value, if present.</param>
/// <returns>An Optional describing the result of applying a mapping function to the value of this Optional, if a value is present, otherwise <see cref="None"/>.</returns>
public Task<Optional<TResult>> Convert<TResult>(Converter<T, Task<Optional<TResult>>> mapper)
=> ConvertOptionalTask<TResult, DelegatingConverter<T, Task<Optional<TResult>>>>(mapper);

/// <summary>
/// If a value is present, apply the provided mapping function to it, and if the result is
/// non-null, return an Optional describing the result. Otherwise returns <see cref="None"/>.
/// </summary>
/// <typeparam name="TResult">The type of the result of the mapping function.</typeparam>
/// <param name="mapper">A mapping function to be applied to the value, if present.</param>
/// <returns>An Optional describing the result of applying a mapping function to the value of this Optional, if a value is present, otherwise <see cref="None"/>.</returns>
[CLSCompliant(false)]
public unsafe Optional<TResult> Convert<TResult>(delegate*<T, Optional<TResult>> mapper)
=> ConvertOptional<TResult, Supplier<T, Optional<TResult>>>(mapper);

/// <summary>
/// If a value is present, apply the provided mapping function to it, and if the result is
/// non-null, return an Optional describing the result. Otherwise returns <see cref="None"/>.
/// </summary>
/// <typeparam name="TResult">The type of the result of the mapping function.</typeparam>
/// <param name="mapper">A mapping function to be applied to the value, if present.</param>
/// <returns>An Optional describing the result of applying a mapping function to the value of this Optional, if a value is present, otherwise <see cref="None"/>.</returns>
[CLSCompliant(false)]
public unsafe Task<Optional<TResult>> Convert<TResult>(delegate*<T, Task<Optional<TResult>>> mapper)
=> ConvertOptionalTask<TResult, Supplier<T, Task<Optional<TResult>>>>(mapper);

/// <inheritdoc cref="IFunctional{TDelegate}.ToDelegate()"/>
Func<object?> IFunctional<Func<object?>>.ToDelegate() => Func.Constant<object?>(kind is NotEmptyValue ? value : null);

Expand Down
Loading