|
| 1 | +package fj.data; |
| 2 | + |
| 3 | +import fj.*; |
| 4 | +import fj.data.State; |
| 5 | +import fj.data.Stream; |
| 6 | +import org.junit.Assert; |
| 7 | +import org.junit.Test; |
| 8 | + |
| 9 | +import static fj.data.Option.some; |
| 10 | +import static fj.data.Stream.unfold; |
| 11 | + |
| 12 | +/** |
| 13 | + * Created by mperry on 4/08/2014. |
| 14 | + */ |
| 15 | +public class StateDemo_Rng { |
| 16 | + |
| 17 | + static String expected1 = "<4,4,2,2,2,5,3,3,1,5>"; |
| 18 | + static int size = 10; |
| 19 | + |
| 20 | + static RNG initRNG() { |
| 21 | + return new SimpleRNG(1); |
| 22 | + } |
| 23 | + |
| 24 | + @Test |
| 25 | + public void testUnfold() { |
| 26 | + Stream<Integer> s = unfold(r -> some(num(r).swap()), initRNG()); |
| 27 | + Assert.assertTrue(s.take(size).toList().toString().equals(expected1)); |
| 28 | + } |
| 29 | + |
| 30 | + @Test |
| 31 | + public void testTransitions() { |
| 32 | + P2<List<State<RNG, Integer>>, State<RNG, Integer>> p = List.replicate(size, nextState()).foldLeft( |
| 33 | + (P2<List<State<RNG, Integer>>, State<RNG, Integer>> p2, F<State<RNG, Integer>, State<RNG, Integer>> f) -> { |
| 34 | + State<RNG, Integer> s = f.f(p2._2()); |
| 35 | + return P.p(p2._1().snoc(p2._2()), s); |
| 36 | + } |
| 37 | + , P.p(List.nil(), defaultState()) |
| 38 | + ); |
| 39 | + List<Integer> ints = p._1().map(s -> s.eval(initRNG())); |
| 40 | + Assert.assertTrue(ints.toString().equals(expected1)); |
| 41 | + } |
| 42 | + |
| 43 | + |
| 44 | + static P2<RNG, Integer> num(RNG r) { |
| 45 | + return r.range(1, 5); |
| 46 | + } |
| 47 | + |
| 48 | + static State<RNG, Integer> defaultState() { |
| 49 | + return State.unit(s -> num(s)); |
| 50 | + } |
| 51 | + |
| 52 | + static F<State<RNG, Integer>, State<RNG, Integer>> nextState() { |
| 53 | + return s -> s.mapState(p2 -> num(p2._1())); |
| 54 | + } |
| 55 | + |
| 56 | + @Test |
| 57 | + public void testSequence() { |
| 58 | + List<Integer> list = State.sequence(List.replicate(size, defaultState())).eval(initRNG()); |
| 59 | + Assert.assertTrue(list.toString().equals(expected1)); |
| 60 | + } |
| 61 | + |
| 62 | +} |
0 commit comments