Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions core/src/main/java/fj/data/State.java
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,24 @@ public State<S, A> withs(F<S, S> f) {
return suspended(s -> runF.f(f.f(s)));
}

/**
* Bind the given function across this state.
*
* @param f the given function
* @param <B> the type of the output value
* @return the state
*/
public <B> State<S, B> bind(F<A, State<S, B>> f) {
return flatMap(f);
}

/**
* Bind the given function across this state.
*
* @param f the given function
* @param <B> the type of the output value
* @return the state
*/
public <B> State<S, B> flatMap(F<A, State<S, B>> f) {
return suspended(s -> runF.f(s).bind(result -> Trampoline.pure(f.f(result._2()).run(result._1()))));
}
Expand Down
39 changes: 36 additions & 3 deletions core/src/test/java/fj/data/StateTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,47 @@

import org.junit.Test;

import static fj.P.p;
import static org.junit.Assert.assertEquals;

/**
* Created by MarkPerry on 18/12/2014.
*/
public class StateTest {

@Test
public void map() {
@Test
public void testBind() {
assertEquals(p(2, "one"), state().run(1));
assertEquals(p(3, "two"), state().run(2));
assertEquals(p(4, "three"), state().run(3));
assertEquals(p(2, "?"), state().bind(state -> State.constant("?")).run(1));
assertEquals(p(3, "?"), state().bind(state -> State.constant("?")).run(2));
assertEquals(p(4, "?"), state().bind(state -> State.constant("?")).run(3));
}

@Test
public void testFlatMap() {
assertEquals(p(2, "one"), state().run(1));
assertEquals(p(3, "two"), state().run(2));
assertEquals(p(4, "three"), state().run(3));
assertEquals(p(2, "?"), state().flatMap(state -> State.constant("?")).run(1));
assertEquals(p(3, "?"), state().flatMap(state -> State.constant("?")).run(2));
assertEquals(p(4, "?"), state().flatMap(state -> State.constant("?")).run(3));
}

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

private static String toLapine(
final int i) {
return i == 1 ?
"one" :
i == 2 ?
"two" :
i == 3 ?
"three" :
i == 4 ?
"four" : "hrair";
}
}