Skip to content

Commit bf890a2

Browse files
committed
Adding the State monad
1 parent 0b7a3f2 commit bf890a2

3 files changed

Lines changed: 299 additions & 0 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ might need to be reworked, and subtyping is obviously no longer supported.
2121
- `MaybeT`, a monad transformer for `Maybe`
2222
- `EitherT`, a monad transformer for `Either`
2323
- `Endo`, a monoid formed by `Fn1` under composition
24+
- `State`, the state `Monad`
2425

2526
## [3.3.0] - 2019-02-18
2627
### Added
Lines changed: 215 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,215 @@
1+
package com.jnape.palatable.lambda.functor.builtin;
2+
3+
import com.jnape.palatable.lambda.adt.Unit;
4+
import com.jnape.palatable.lambda.adt.hlist.HList;
5+
import com.jnape.palatable.lambda.adt.hlist.Tuple2;
6+
import com.jnape.palatable.lambda.adt.product.Product2;
7+
import com.jnape.palatable.lambda.functions.Fn1;
8+
import com.jnape.palatable.lambda.functor.Applicative;
9+
import com.jnape.palatable.lambda.monad.Monad;
10+
11+
import java.util.function.Function;
12+
13+
import static com.jnape.palatable.lambda.adt.Unit.UNIT;
14+
import static com.jnape.palatable.lambda.adt.hlist.HList.tuple;
15+
import static com.jnape.palatable.lambda.functions.builtin.fn1.Constantly.constantly;
16+
import static com.jnape.palatable.lambda.functions.builtin.fn1.Id.id;
17+
import static com.jnape.palatable.lambda.functions.builtin.fn2.Both.both;
18+
import static com.jnape.palatable.lambda.functions.builtin.fn2.Into.into;
19+
20+
/**
21+
* The state {@link Monad}, useful for iteratively building up state and state-contextualized result.
22+
* <p>
23+
* For more information, read about the
24+
* <a href="https://en.wikibooks.org/wiki/Haskell/Understanding_monads/State" target="_blank">state monad</a>.
25+
*
26+
* @param <S> the state type
27+
* @param <A> the result type
28+
*/
29+
public final class State<S, A> implements Monad<A, State<S, ?>> {
30+
31+
private final Fn1<? super S, ? extends Tuple2<A, S>> stateFn;
32+
33+
private State(Fn1<? super S, ? extends Tuple2<A, S>> stateFn) {
34+
this.stateFn = stateFn;
35+
}
36+
37+
/**
38+
* Run the stateful computation, returning a {@link Tuple2} of the result and the final state.
39+
*
40+
* @param s the initial state
41+
* @return a {@link Tuple2} of the result and the final state.
42+
*/
43+
public Tuple2<A, S> run(S s) {
44+
return stateFn.apply(s).into(HList::tuple);
45+
}
46+
47+
/**
48+
* Run the stateful computation, returning the result.
49+
*
50+
* @param s the initial state
51+
* @return the result
52+
*/
53+
public A eval(S s) {
54+
return run(s)._1();
55+
}
56+
57+
/**
58+
* Run the stateful computation, returning the final state.
59+
*
60+
* @param s the initial state
61+
* @return the final state
62+
*/
63+
public S exec(S s) {
64+
return run(s)._2();
65+
}
66+
67+
/**
68+
* Map both the result and the final state to a new result and final state.
69+
*
70+
* @param fn the mapping function
71+
* @param <B> the potentially new final state type
72+
* @return the mapped {@link State}
73+
*/
74+
public <B> State<S, B> mapState(Fn1<? super Tuple2<A, S>, ? extends Product2<B, S>> fn) {
75+
return state(s -> fn.apply(run(s)));
76+
}
77+
78+
/**
79+
* Map the final state to a new final state using the provided function.
80+
*
81+
* @param fn the state-mapping function
82+
* @return the mapped {@link State}
83+
*/
84+
public State<S, A> withState(Fn1<? super S, ? extends S> fn) {
85+
return state(s -> run(fn.apply(s)));
86+
}
87+
88+
/**
89+
* {@inheritDoc}
90+
*/
91+
@Override
92+
public <B> State<S, B> flatMap(Function<? super A, ? extends Monad<B, State<S, ?>>> f) {
93+
return state(s -> run(s).into((a, s2) -> f.apply(a).<State<S, B>>coerce().run(s2)));
94+
}
95+
96+
/**
97+
* {@inheritDoc}
98+
*/
99+
@Override
100+
public <B> State<S, B> pure(B b) {
101+
return state(s -> tuple(b, s));
102+
}
103+
104+
/**
105+
* {@inheritDoc}
106+
*/
107+
@Override
108+
public <B> State<S, B> fmap(Function<? super A, ? extends B> fn) {
109+
return Monad.super.<B>fmap(fn).coerce();
110+
}
111+
112+
/**
113+
* {@inheritDoc}
114+
*/
115+
@Override
116+
public <B> State<S, B> zip(Applicative<Function<? super A, ? extends B>, State<S, ?>> appFn) {
117+
return Monad.super.zip(appFn).coerce();
118+
}
119+
120+
/**
121+
* {@inheritDoc}
122+
*/
123+
@Override
124+
public <B> Lazy<State<S, B>> lazyZip(
125+
Lazy<? extends Applicative<Function<? super A, ? extends B>, State<S, ?>>> lazyAppFn) {
126+
return Monad.super.lazyZip(lazyAppFn).fmap(Monad<B, State<S, ?>>::coerce);
127+
}
128+
129+
/**
130+
* {@inheritDoc}
131+
*/
132+
@Override
133+
public <B> State<S, A> discardR(Applicative<B, State<S, ?>> appB) {
134+
return Monad.super.discardR(appB).coerce();
135+
}
136+
137+
/**
138+
* {@inheritDoc}
139+
*/
140+
@Override
141+
public <B> State<S, B> discardL(Applicative<B, State<S, ?>> appB) {
142+
return Monad.super.discardL(appB).coerce();
143+
}
144+
145+
/**
146+
* Create a {@link State} that simply returns back the initial state as both the result and the final state
147+
*
148+
* @param <A> the state and result type
149+
* @return the new {@link State} instance
150+
*/
151+
@SuppressWarnings("RedundantTypeArguments")
152+
public static <A> State<A, A> get() {
153+
return new State<>(Tuple2::<A>fill);
154+
}
155+
156+
/**
157+
* Create a {@link State} that ignores its initial state, returning a {@link Unit} result and <code>s</code> as its
158+
* final state.
159+
*
160+
* @param s the final state
161+
* @param <S> the state type
162+
* @return the new {@link State} instance
163+
*/
164+
public static <S> State<S, Unit> put(S s) {
165+
return new State<>(constantly(tuple(UNIT, s)));
166+
}
167+
168+
/**
169+
* Create a {@link State} that maps its initial state into its result, but leaves the initial state unchanged.
170+
*
171+
* @param fn the mapping function
172+
* @param <S> the state type
173+
* @param <A> the result type
174+
* @return the new {@link State} instance
175+
*/
176+
public static <S, A> State<S, A> gets(Fn1<? super S, ? extends A> fn) {
177+
return state(both(fn, id()));
178+
}
179+
180+
/**
181+
* Create a {@link State} that maps its initial state into its final state, returning a {@link Unit} result type.
182+
*
183+
* @param fn the mapping function
184+
* @param <S> the state type
185+
* @return the new {@link State} instance
186+
*/
187+
public static <S> State<S, Unit> modify(Fn1<? super S, ? extends S> fn) {
188+
return state(both(constantly(UNIT), fn));
189+
}
190+
191+
/**
192+
* Create a {@link State} from <code>stateFn</code>, a function that maps an initial state into a result and a final
193+
* state.
194+
*
195+
* @param stateFn the state function
196+
* @param <S> the state type
197+
* @param <A> the result type
198+
* @return the new {@link State} instance
199+
*/
200+
public static <S, A> State<S, A> state(Fn1<? super S, ? extends Product2<A, S>> stateFn) {
201+
return new State<>(stateFn.fmap(into(HList::tuple)));
202+
}
203+
204+
/**
205+
* Create a {@link State} that returns <code>a</code> as its result and its initial state as its final state.
206+
*
207+
* @param a the result
208+
* @param <S> the state type
209+
* @param <A> the result type
210+
* @return the new {@link State} instance
211+
*/
212+
public static <S, A> State<S, A> state(A a) {
213+
return gets(constantly(a));
214+
}
215+
}
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
package com.jnape.palatable.lambda.functor.builtin;
2+
3+
import com.jnape.palatable.lambda.adt.Unit;
4+
import com.jnape.palatable.lambda.adt.hlist.HList;
5+
import com.jnape.palatable.traitor.annotations.TestTraits;
6+
import com.jnape.palatable.traitor.runners.Traits;
7+
import org.junit.Test;
8+
import org.junit.runner.RunWith;
9+
import testsupport.EquatableM;
10+
import testsupport.traits.ApplicativeLaws;
11+
import testsupport.traits.FunctorLaws;
12+
import testsupport.traits.MonadLaws;
13+
14+
import static com.jnape.palatable.lambda.adt.Unit.UNIT;
15+
import static com.jnape.palatable.lambda.adt.hlist.HList.tuple;
16+
import static com.jnape.palatable.lambda.adt.product.Product2.product;
17+
import static com.jnape.palatable.lambda.functions.builtin.fn2.Into.into;
18+
import static org.junit.Assert.assertEquals;
19+
20+
@RunWith(Traits.class)
21+
public class StateTest {
22+
23+
@TestTraits({FunctorLaws.class, ApplicativeLaws.class, MonadLaws.class})
24+
public EquatableM<State<Unit, ?>, Unit> testSubject() {
25+
return new EquatableM<>(State.get(), state -> state.run(UNIT).into(HList::tuple));
26+
}
27+
28+
@Test
29+
public void eval() {
30+
State<Integer, Unit> state = State.put(0);
31+
assertEquals(state.run(1)._1(), state.eval(1));
32+
}
33+
34+
@Test
35+
public void exec() {
36+
State<Integer, Unit> state = State.put(0);
37+
assertEquals(state.run(1)._2(), state.exec(1));
38+
}
39+
40+
@Test
41+
public void get() {
42+
assertEquals(tuple(1, 1), State.<Integer>get().run(1));
43+
}
44+
45+
@Test
46+
public void put() {
47+
assertEquals(tuple(UNIT, 1), State.put(1).run(1));
48+
}
49+
50+
@Test
51+
public void gets() {
52+
assertEquals(tuple(0, "0"), State.<String, Integer>gets(Integer::parseInt).run("0"));
53+
}
54+
55+
@Test
56+
public void modify() {
57+
assertEquals(tuple(UNIT, 1), State.<Integer>modify(x -> x + 1).run(0));
58+
}
59+
60+
@Test
61+
public void state() {
62+
assertEquals(tuple(1, UNIT), State.<Unit, Integer>state(1).run(UNIT));
63+
assertEquals(tuple(1, -1), State.<Integer, Integer>state(x -> product(x + 1, x - 1)).run(0));
64+
}
65+
66+
@Test
67+
public void stateAccumulation() {
68+
State<Integer, Integer> counter = State.<Integer>get().flatMap(i -> State.put(i + 1).discardL(State.state(i)));
69+
assertEquals(tuple(0, 1), counter.run(0));
70+
}
71+
72+
@Test
73+
public void withState() {
74+
State<Integer, Integer> modified = State.<Integer>get().withState(x -> x + 1);
75+
assertEquals(tuple(1, 1), modified.run(0));
76+
}
77+
78+
@Test
79+
public void mapState() {
80+
State<Integer, Integer> modified = State.<Integer>get().mapState(into((a, s) -> product(a + 1, s + 2)));
81+
assertEquals(tuple(1, 2), modified.run(0));
82+
}
83+
}

0 commit comments

Comments
 (0)