Skip to content

Commit 849dc39

Browse files
Fixes #417. Add fj.data.State.bind(F<A, State<S, B>>).
1 parent 1fa07b4 commit 849dc39

File tree

2 files changed

+54
-3
lines changed

2 files changed

+54
-3
lines changed

core/src/main/java/fj/data/State.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,24 @@ public State<S, A> withs(F<S, S> f) {
111111
return suspended(s -> runF.f(f.f(s)));
112112
}
113113

114+
/**
115+
* Bind the given function across this state.
116+
*
117+
* @param f the given function
118+
* @param <B> the type of the output value
119+
* @return the state
120+
*/
121+
public <B> State<S, B> bind(F<A, State<S, B>> f) {
122+
return flatMap(f);
123+
}
124+
125+
/**
126+
* Bind the given function across this state.
127+
*
128+
* @param f the given function
129+
* @param <B> the type of the output value
130+
* @return the state
131+
*/
114132
public <B> State<S, B> flatMap(F<A, State<S, B>> f) {
115133
return suspended(s -> runF.f(s).bind(result -> Trampoline.pure(f.f(result._2()).run(result._1()))));
116134
}

core/src/test/java/fj/data/StateTest.java

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,47 @@
22

33
import org.junit.Test;
44

5+
import static fj.P.p;
6+
import static org.junit.Assert.assertEquals;
7+
58
/**
69
* Created by MarkPerry on 18/12/2014.
710
*/
811
public class StateTest {
912

10-
@Test
11-
public void map() {
13+
@Test
14+
public void testBind() {
15+
assertEquals(p(2, "one"), state().run(1));
16+
assertEquals(p(3, "two"), state().run(2));
17+
assertEquals(p(4, "three"), state().run(3));
18+
assertEquals(p(2, "?"), state().bind(state -> State.constant("?")).run(1));
19+
assertEquals(p(3, "?"), state().bind(state -> State.constant("?")).run(2));
20+
assertEquals(p(4, "?"), state().bind(state -> State.constant("?")).run(3));
21+
}
22+
23+
@Test
24+
public void testFlatMap() {
25+
assertEquals(p(2, "one"), state().run(1));
26+
assertEquals(p(3, "two"), state().run(2));
27+
assertEquals(p(4, "three"), state().run(3));
28+
assertEquals(p(2, "?"), state().flatMap(state -> State.constant("?")).run(1));
29+
assertEquals(p(3, "?"), state().flatMap(state -> State.constant("?")).run(2));
30+
assertEquals(p(4, "?"), state().flatMap(state -> State.constant("?")).run(3));
31+
}
1232

13-
}
33+
private static final State<Integer, String> state() {
34+
return State.<Integer, String>unit(i -> p(i + 1, toLapine(i)));
35+
}
1436

37+
private static String toLapine(
38+
final int i) {
39+
return i == 1 ?
40+
"one" :
41+
i == 2 ?
42+
"two" :
43+
i == 3 ?
44+
"three" :
45+
i == 4 ?
46+
"four" : "hrair";
47+
}
1548
}

0 commit comments

Comments
 (0)