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 1 commit 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
114 changes: 114 additions & 0 deletions src/DotNext/Optional.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

namespace DotNext;

using System.Threading.Tasks;
using Runtime.CompilerServices;
using Intrinsics = Runtime.Intrinsics;

Expand Down Expand Up @@ -58,6 +59,18 @@ public static async Task<T> Flatten<T>(this Task<Optional<T>> task)
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)
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 provides a little value, because it's already covered by Conversion.Convert. Also, Flatten method can be used to convert Task<Optional<T>> to Task<T> in the beginning of the async chain.

Instead

Task<Optional<int>> task = Task.FromResult(Optional.Some(42));
Optional<int> result = await task.Convert(i => i);
Task<Optional<int>> task = Task.FromResult(Optional.Some(42));
int result = await task.Flatten().Convert(i => i);

Also, the similar behavior can be achieved by using SuspendException which returns Result<T>. Result<T> has implicit conversion to Optional<T>, so the chain above can be rewritten easily with existing API:

Task<Optional<int>> task = Task.FromResult(Optional.Some(42));
Optional<int> result = await task.Flatten().Convert(i => i).SuspendException(); // implicit conversion from Result<T> to Optional<T>

=> (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"/>.
Expand All @@ -79,6 +92,66 @@ public static async Task<Optional<TOutput>> Convert<TInput, TOutput>(this Task<O
: Optional<TOutput>.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="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>
/// <param name="token">The token that can be used to cancel the operation.</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,
Func<TInput, CancellationToken, Task<Optional<TOutput>>> converter, CancellationToken token = default)
{
var optional = await task.ConfigureAwait(false);
return optional.HasValue
? await converter.Invoke(optional.ValueOrDefault, token).ConfigureAwait(false)
: optional.IsNull && Intrinsics.IsNullable<TOutput>()
? new(default)
: Optional<TOutput>.None;
}

/// <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)
Copy link
Collaborator

Choose a reason for hiding this comment

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

There is explicit conversion operator in Result<T> type, so you can use casting syntax:

Optional<int> value = 42;
var result = (Result<int>)value;

=> 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)
Copy link
Collaborator

Choose a reason for hiding this comment

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

Task<Result<T>> is redundant type, this conversion makes no sense. There is Flatten method that converts Task<Optional<T>> to Task<T>.

=> 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)
Copy link
Collaborator

Choose a reason for hiding this comment

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

Task<Result<T, TError>> is a redundant type.

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 @@ -609,6 +682,47 @@ public Optional<TResult> Convert<TResult>(Converter<T, Optional<TResult>> mapper
public unsafe Optional<TResult> Convert<TResult>(delegate*<T, Optional<TResult>> mapper)
=> ConvertOptional<TResult, Supplier<T, Optional<TResult>>>(mapper);

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private async Task<Optional<TResult>> ConvertTask<TResult>(Func<T, CancellationToken, Task<TResult>> converter, CancellationToken token = default)
=> HasValue ? await converter.Invoke(value, token).ConfigureAwait(false) : 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"/>.
/// </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>
/// <param name="token">The token that can be used to cancel the operation.</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>(Func<T, CancellationToken, Task<TResult>> mapper, CancellationToken token = default)
Copy link
Collaborator

Choose a reason for hiding this comment

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

The method is redundant, since SuspendException returns Result<T> that has implicit conversion to Optional<T>.

=> ConvertTask(mapper, token);

[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"/>.
/// </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>
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 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
Loading