diff --git a/src/main/java/net/kemitix/conditional/Condition.java b/src/main/java/net/kemitix/conditional/Condition.java index 8bfee11..4fe2d15 100644 --- a/src/main/java/net/kemitix/conditional/Condition.java +++ b/src/main/java/net/kemitix/conditional/Condition.java @@ -21,6 +21,7 @@ package net.kemitix.conditional; +import java.util.function.Function; import java.util.function.Supplier; /** @@ -183,4 +184,13 @@ public interface Condition { @SuppressWarnings(SuppressHelper.CS_ILLEGALTHROWS) void otherwiseThrow(Exception exception) throws Exception; + /** + * Apply the function to the Condtion, resulting an another Condition. + * + * @param f the function to apply + * @return a new Condition + */ + default Condition flatMap(final Function f) { + return f.apply(isTrue()); + } } diff --git a/src/test/java/net/kemitix/conditional/ConditionMonadTest.java b/src/test/java/net/kemitix/conditional/ConditionMonadTest.java new file mode 100644 index 0000000..74307b2 --- /dev/null +++ b/src/test/java/net/kemitix/conditional/ConditionMonadTest.java @@ -0,0 +1,45 @@ +package net.kemitix.conditional; + +import org.assertj.core.api.WithAssertions; +import org.junit.Test; + +import java.util.function.Function; + +public class ConditionMonadTest implements WithAssertions { + + private final boolean v = true; + private final Function f = i -> r(true); + private final Function g = i -> r(i); + + private static Condition r(boolean v) { + return Condition.where(v); + } + + @Test + public void leftIdentity() { + assertThat( + r(v).flatMap(f) + ).isEqualTo( + f.apply(v) + ); + } + + @Test + public void rightIdentity() { + assertThat( + r(v).flatMap(x -> r(x)) + ).isEqualTo( + r(v) + ); + } + + @Test + public void associativity() { + assertThat( + r(v).flatMap(f).flatMap(g) + ).isEqualTo( + r(v).flatMap(x -> f.apply(x).flatMap(g)) + ); + } + +}