Skip to content

Commit

Permalink
Adding more tests
Browse files Browse the repository at this point in the history
  • Loading branch information
jabrena committed Jun 2, 2024
1 parent ecbe075 commit 4fc9a77
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 7 deletions.
2 changes: 1 addition & 1 deletion training/src/main/java/info/jab/fp/util/Either.java
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ default <U> Either<L, U> map(Function<? super R, ? extends U> mapper) {
* @param <U> the type of the new Right value
* @return a new Either instance
*/
default <U> Either<L, U> flatMap(Function<? super R, Either<L, U>> mapper) {
default <U> Either<L, U> flatMap(Function<? super R, ? extends Either<L, U>> mapper) {
if (isRight()) {
return mapper.apply(((Right<L, R>) this).value());
} else {
Expand Down
45 changes: 45 additions & 0 deletions training/src/test/java/info/jab/fp/util/EitherMonadLawsTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package info.jab.fp.util;

import java.util.function.Function;

import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;

class EitherMonadLawsTest {

// Left Identity: return a >>= f ≡ f a
@Test
void testLeftIdentity() {
Function<Integer, Either<String, Integer>> f = x -> Either.right(x + 1);
Integer a = 42;

Either<String, Integer> leftIdentity = Either.<String, Integer>right(a).flatMap(f);
Either<String, Integer> expected = f.apply(a);

assertEquals(expected, leftIdentity);
}

// Right Identity: m >>= return ≡ m
@Test
void testRightIdentity() {
Either<String, Integer> m = Either.right(42);

Either<String, Integer> rightIdentity = m.flatMap(Either::right);

assertEquals(m, rightIdentity);
}

// Associativity: (m >>= f) >>= g ≡ m >>= (\x -> f x >>= g)
@Test
void testAssociativity() {
Function<Integer, Either<String, Integer>> f = x -> Either.right(x + 1);
Function<Integer, Either<String, Integer>> g = x -> Either.right(x * 2);

Either<String, Integer> m = Either.right(42);

Either<String, Integer> leftAssociative = m.flatMap(f).flatMap(g);
Either<String, Integer> rightAssociative = m.flatMap(x -> f.apply(x).flatMap(g));

assertEquals(leftAssociative, rightAssociative);
}
}
6 changes: 0 additions & 6 deletions training/src/test/java/info/jab/fp/util/EitherTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,6 @@

public class EitherTest {

@Test
public void testFold() {
Either<String, Integer> success = Either.right(42);
Either<String, Integer> failure = Either.left("Error occurred");
}

@Test
void testLeft() {
Either<String, Integer> left = Either.left("Error");
Expand Down

0 comments on commit 4fc9a77

Please sign in to comment.