Files
SjkScripts/Functional/IOption.cs

52 lines
2.4 KiB
C#
Raw Normal View History

2026-04-04 13:18:04 -04:00
using System.Diagnostics.CodeAnalysis;
namespace SJK.Functional;
public interface IOption<T> : IEquatable<IOption<T>>
{
/// <summary>
/// Applies a function to the contained value if it exists (is not None), otherwise applies a default function.
/// </summary>
/// <param name="onSome">Function to apply if the option contains a value.</param>
/// <param name="onNone">Function to apply if the option does not contain a value.</param>
/// <returns>The result of applying either the onSome or onNone function.</returns>
TResult Match<TResult>(Func<T, TResult> onSome, Func<TResult> onNone);
void Match(Action<T> onSome,Action onNone);
/// <summary>
/// Chains operations on the contained value using a function that returns an option.
/// </summary>
/// <param name="f">A function that takes the contained value and returns an option.</param>
/// <returns>An option resulting from applying the function f to the contained value.</returns>
IOption<TResult> Bind<TResult>(Func<T, IOption<TResult>> f);
/// <summary>
/// Maps a function over the contained value if it exists (is not None).
/// </summary>
/// <param name="f">The function to apply to the contained value.</param>
/// <returns>An option containing the result of applying f to the contained value.</returns>
IOption<TResult> Map<TResult>(Func<T, TResult> f);
/// <summary>
/// Returns the contained value if it exists (is not None), otherwise returns the provided default value.
/// </summary>
/// <param name="aDefault">The default value to return if the option does not contain a value.</param>
/// <returns>The contained value or the default value.</returns>
T Or(T aDefault);
/// <summary>
/// Returns the contained value if it exists (is not None), otherwise calls the provided default function.
/// </summary>
/// <param name="aDefault">The default value to return if the option does not contain a value.</param>
/// <returns>The contained value or the default value.</returns>
T Or(Func<T> aDefault);
/// <summary>
/// Checks if the option contains a value (is not None) and outputs it if true.
/// </summary>
/// <param name="value">An out parameter that will be assigned the contained value if it exists.</param>
/// <returns>true if the option contains a value; false otherwise.</returns>
bool HasValue([NotNullWhen(true)]out T? value);
// [Obsolete]
bool HasValue();
}