Condition.flatMap() added with Monad tests
This commit is contained in:
parent
80e813e933
commit
e853894382
2 changed files with 55 additions and 0 deletions
|
@ -21,6 +21,7 @@
|
||||||
|
|
||||||
package net.kemitix.conditional;
|
package net.kemitix.conditional;
|
||||||
|
|
||||||
|
import java.util.function.Function;
|
||||||
import java.util.function.Supplier;
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -183,4 +184,13 @@ public interface Condition {
|
||||||
@SuppressWarnings(SuppressHelper.CS_ILLEGALTHROWS)
|
@SuppressWarnings(SuppressHelper.CS_ILLEGALTHROWS)
|
||||||
void otherwiseThrow(Exception exception) throws Exception;
|
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<Boolean, Condition> f) {
|
||||||
|
return f.apply(isTrue());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -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<Boolean, Condition> f = i -> r(true);
|
||||||
|
private final Function<Boolean, Condition> 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))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
Loading…
Reference in a new issue