Result satisfies the three Monad Laws

This commit is contained in:
Paul Campbell 2018-06-25 22:39:25 +01:00
parent 5d39be36ff
commit 093e35b4c1
3 changed files with 52 additions and 0 deletions

View file

@ -101,6 +101,8 @@ class Test {
### Result
A Monad.
A container for method return values that may raise an Exception. Useful for when a checked exceptions can't be added
to the method signature.

View file

@ -24,6 +24,7 @@ package net.kemitix.mon.result;
import lombok.RequiredArgsConstructor;
import net.kemitix.mon.maybe.Maybe;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
@ -76,6 +77,16 @@ class Success<T> implements Result<T> {
return value;
}
@Override
public boolean equals(Object other) {
return other instanceof Success && Objects.equals(value, ((Success) other).value);
}
@Override
public int hashCode() {
return Objects.hash(value);
}
@Override
public String toString() {
return String.format("Result.Success{value=%s}", value);

View file

@ -0,0 +1,39 @@
package net.kemitix.mon;
import net.kemitix.mon.result.Result;
import org.assertj.core.api.WithAssertions;
import org.junit.Test;
import java.util.function.Function;
public class ResultMonadTest implements WithAssertions {
@Test
public void leftIdentity() {
//given
final int value = 1;
final Result<Integer> result = Result.ok(value);
final Function<Integer, Result<Integer>> f = i -> Result.ok(i * 2);
//then
assertThat(result.flatMap(f)).isEqualTo(f.apply(value));
}
@Test
public void rightIdentity() {
//given
final Result<Integer> result = Result.ok(1);
//then
assertThat(result.flatMap(Result::ok)).isEqualTo(result);
}
@Test
public void associativity() {
//given
final Result<Integer> result = Result.ok(1);
final Function<Integer, Result<Integer>> f = i -> Result.ok(i * 2);
final Function<Integer, Result<Integer>> g = i -> Result.ok(i + 6);
//then
assertThat(result.flatMap(f).flatMap(g)).isEqualTo(result.flatMap(x -> f.apply(x).flatMap(g)));
}
}