Skip to content

Commit 17671fc

Browse files
committed
Adding function composition
1 parent 8f9aa01 commit 17671fc

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,16 @@
11
package com.jnape.palatable.lambda;
22

33
public abstract class MonadicFunction<A, B> {
4+
45
public abstract B apply(A a);
6+
7+
public final <C> MonadicFunction<A, C> then(final MonadicFunction<B, C> f) {
8+
return new MonadicFunction<A, C>() {
9+
@Override
10+
public C apply(A a) {
11+
MonadicFunction<A, B> g = MonadicFunction.this;
12+
return f.apply(g.apply(a));
13+
}
14+
};
15+
}
516
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package com.jnape.palatable.lambda;
2+
3+
import org.junit.Test;
4+
5+
import static org.hamcrest.MatcherAssert.assertThat;
6+
import static org.hamcrest.core.Is.is;
7+
8+
public class MonadicFunctionTest {
9+
10+
@Test
11+
public void composesByApplyingFunctionThenForwardingToNextFunction() {
12+
MonadicFunction<Integer, Integer> add2 = new MonadicFunction<Integer, Integer>() {
13+
@Override
14+
public Integer apply(Integer integer) {
15+
return integer + 2;
16+
}
17+
};
18+
MonadicFunction<Integer, String> toString = new MonadicFunction<Integer, String>() {
19+
@Override
20+
public String apply(Integer integer) {
21+
return integer.toString();
22+
}
23+
};
24+
25+
assertThat(add2.then(toString).apply(2), is(toString.apply(add2.apply(2))));
26+
}
27+
}

0 commit comments

Comments
 (0)