From ef3a54eae788c1c6134f210e34060d880ddd1823 Mon Sep 17 00:00:00 2001 From: Kyle Ratti Date: Sun, 17 Dec 2023 13:47:16 -0500 Subject: [PATCH] fix: use correct signature on bind --- Base.Tests/Structures/MaybeTests.cs | 45 +++++++++++++++++++++++++++++ Base/Structures/Maybe.cs | 2 +- 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 Base.Tests/Structures/MaybeTests.cs diff --git a/Base.Tests/Structures/MaybeTests.cs b/Base.Tests/Structures/MaybeTests.cs new file mode 100644 index 0000000..4acf46a --- /dev/null +++ b/Base.Tests/Structures/MaybeTests.cs @@ -0,0 +1,45 @@ +using FruityFoundation.Base.Structures; +using NUnit.Framework; + +namespace Base.Tests.Structures; + +public class MaybeTests +{ + [Test] + public void TestBind_DoesNotBindEmptyValue() + { + var emptyMaybe = Maybe.Empty(); + + var result = emptyMaybe.Bind(x => Maybe.Just(x + 1)); + + Assert.That(result, Is.InstanceOf>()); + Assert.That(result.HasValue, Is.False); + } + + [Test] + public void TestBind_BindsWhenHasValue() + { + var emptyMaybe = Maybe.Just(1); + + var result = emptyMaybe.Bind(x => Maybe.Just(x + 1)); + + Assert.That(result, Is.InstanceOf>()); + Assert.That(result.HasValue, Is.True); + Assert.That(result.Value, Is.EqualTo(2)); + } + + [Test] + public void TestBind_BindsWhenHasValue_NewOutputType() + { + var maybe = Maybe.Just(25); + + var result = maybe.Bind(x => x switch + { + 25 => Maybe.Just("twenty-five"), + _ => Maybe.Empty() + }); + + Assert.That(result, Is.InstanceOf>()); + Assert.That(result.HasValue, Is.True); + } +} diff --git a/Base/Structures/Maybe.cs b/Base/Structures/Maybe.cs index 5b375e3..d319b7c 100644 --- a/Base/Structures/Maybe.cs +++ b/Base/Structures/Maybe.cs @@ -54,7 +54,7 @@ public readonly struct Maybe public Maybe Map(Func transformer) => HasValue ? Maybe.Just(transformer(Value)) : Maybe.Empty(); - public Maybe Bind(Func binder) => + public Maybe Bind(Func> binder) => HasValue ? binder(Value) : Maybe.Empty(); public Maybe Cast()