feat: Maybe<T>.EmptyBind

This commit is contained in:
Kyle Ratti 2023-12-25 14:37:58 -05:00
parent 35d78ee0a5
commit 8e007975f6
No known key found for this signature in database
GPG Key ID: 4D429B6287C68DD9
2 changed files with 54 additions and 0 deletions

View File

@ -42,4 +42,52 @@ public class MaybeTests
Assert.That(result, Is.InstanceOf<Maybe<string>>()); Assert.That(result, Is.InstanceOf<Maybe<string>>());
Assert.That(result.HasValue, Is.True); Assert.That(result.HasValue, Is.True);
} }
[Test]
public void EmptyBind_DoesNotBindFactory_WhenHasValue()
{
var maybe = Maybe.Just(25);
var result = maybe.EmptyBind(() => Maybe.Just(30));
Assert.That(result, Is.InstanceOf<Maybe<int>>());
Assert.That(result.HasValue, Is.True);
Assert.That(result.Value, Is.EqualTo(25));
}
[Test]
public void EmptyBind_BindsFactory_WhenDoesNotHaveValue()
{
var maybe = Maybe.Empty<int>();
var result = maybe.EmptyBind(() => Maybe.Just(30));
Assert.That(result, Is.InstanceOf<Maybe<int>>());
Assert.That(result.HasValue, Is.True);
Assert.That(result.Value, Is.EqualTo(30));
}
[Test]
public void EmptyBind_DoesNotBindMaybe_WhenHasValue()
{
var maybe = Maybe.Just(25);
var result = maybe.EmptyBind(Maybe.Just(30));
Assert.That(result, Is.InstanceOf<Maybe<int>>());
Assert.That(result.HasValue, Is.True);
Assert.That(result.Value, Is.EqualTo(25));
}
[Test]
public void EmptyBind_BindsMaybe_WhenDoesNotHaveValue()
{
var maybe = Maybe.Empty<int>();
var result = maybe.EmptyBind(Maybe.Just(30));
Assert.That(result, Is.InstanceOf<Maybe<int>>());
Assert.That(result.HasValue, Is.True);
Assert.That(result.Value, Is.EqualTo(30));
}
} }

View File

@ -57,6 +57,12 @@ public readonly struct Maybe<T>
public Maybe<TOutput> Bind<TOutput>(Func<T, Maybe<TOutput>> binder) => public Maybe<TOutput> Bind<TOutput>(Func<T, Maybe<TOutput>> binder) =>
HasValue ? binder(Value) : Maybe.Empty<TOutput>(); HasValue ? binder(Value) : Maybe.Empty<TOutput>();
public Maybe<T> EmptyBind(Func<Maybe<T>> maybeFactory) =>
HasValue ? this : maybeFactory();
public Maybe<T> EmptyBind(Maybe<T> maybe) =>
HasValue ? this : maybe;
public Maybe<TOutput> Cast<TOutput>() public Maybe<TOutput> Cast<TOutput>()
{ {
if (!HasValue) if (!HasValue)