BAEL-5960 - Functors in Java (#13125)

This commit is contained in:
alemoles 2022-12-05 04:02:24 -03:00 committed by GitHub
parent bb57868ec9
commit 316cd48b48
3 changed files with 96 additions and 0 deletions

View File

@ -0,0 +1,23 @@
package com.baeldung.functional.functors;
public enum EnumFunctor {
PLUS {
public int apply(int a, int b) {
return a + b;
}
}, MINUS {
public int apply(int a, int b) {
return a - b;
}
}, MULTIPLY {
public int apply(int a, int b) {
return a * b;
}
}, DIVIDE {
public int apply(int a, int b) {
return a / b;
}
};
public abstract int apply(int a, int b);
}

View File

@ -0,0 +1,23 @@
package com.baeldung.functional.functors;
import java.util.function.Function;
public class Functor<T> {
private final T value;
public Functor(T value) {
this.value = value;
}
public <R> Functor<R> map(Function<T, R> mapper) {
return new Functor<>(mapper.apply(value));
}
boolean eq(T other) {
return value.equals(other);
}
public T getValue() {
return value;
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.functional.functors;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.function.Function;
import org.junit.jupiter.api.Test;
class FunctorsUnitTest {
@Test
public void whenProvideAValue_ShouldMapTheValue() {
Functor<Integer> functor = new Functor<>(5);
Function<Integer, Integer> addThree = (num) -> num + 3;
Functor<Integer> mappedFunctor = functor.map(addThree);
assertEquals(8, mappedFunctor.getValue());
}
@Test
public void whenApplyAnIdentityToAFunctor_thenResultIsEqualsToInitialValue() {
String value = "baeldung";
//Identity
Functor<String> identity = new Functor<>(value).map(Function.identity());
assertTrue(identity.eq(value));
}
@Test
public void whenApplyAFunctionToOtherFunction_thenResultIsEqualsBetweenBoth() {
int value = 100;
long expected = 100;
// Composition/Associativity
Function<Integer, String> f = Object::toString;
Function<String, Long> g = Long::valueOf;
Functor<Long> left = new Functor<>(value).map(f)
.map(g);
Functor<Long> right = new Functor<>(value).map(f.andThen(g));
assertTrue(left.eq(expected));
assertTrue(right.eq(expected));
}
@Test
public void whenApplyOperationsToEnumFunctors_thenGetTheProperResult() {
assertEquals(15, EnumFunctor.PLUS.apply(10, 5));
assertEquals(5, EnumFunctor.MINUS.apply(10, 5));
assertEquals(50, EnumFunctor.MULTIPLY.apply(10, 5));
assertEquals(2, EnumFunctor.DIVIDE.apply(10, 5));
}
}