summaryrefslogtreecommitdiff
path: root/src/main/java/au/id/zancanaro/Generators.java
blob: e0927ffa07936a21129f1bb71d6cded64bce5bd0 (about) (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package au.id.zancanaro;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.function.Predicate;

public class Generators {
    public static <T> Generator<T> suchThat(Generator<T> gen, Predicate<T> pred) {
        return (random, size) -> {
            RoseTree<T> result = gen.generate(random, size);
            if (pred.test(result.getValue())) {
                return result.filter(pred);
            } else {
                return suchThat(gen, pred).generate(random, size);
            }
        };
    }

    @SafeVarargs
    public static <T> Generator<T> oneOf(Generator<T>... gens) {
        return integer(0, gens.length).flatMap(index -> gens[index]);
    }

    public static Generator<Integer> integer(int lower, int upper) {
        return (random, size) -> {
            int value = lower + random.nextInt(upper - lower);
            int bound = lower > 0 ? lower : (upper < 0 ? upper : 0);
            return new RoseTree<>(value, intShrinkingIterable(value, bound));
        };
    }

    public static Generator<Integer> integer() {
        return (random, size) -> integer(-size, size).generate(random, size);
    }

    public static Generator<Integer> natural() {
        return (random, size) -> integer(0, size).generate(random, size);
    }

    private static Iterable<RoseTree<Integer>> intShrinkingIterable(final int value, final int bound) {
        return () -> new Iterator<RoseTree<Integer>>() {
            int curr = value - bound;

            @Override
            public boolean hasNext() {
                return curr != 0;
            }

            @Override
            public RoseTree<Integer> next() {
                int prevCurr = curr;
                curr = curr / 2;
                return new RoseTree<>(value - prevCurr, intShrinkingIterable(value - prevCurr, bound));
            }
        };
    }

    public static <T> Generator<List<T>> listOf(Generator<T> gen) {
        return (random, size) -> integer(0, size).flatMap(count -> {
            @SuppressWarnings("unchecked")
            Generator<T>[] gens = (Generator<T>[]) new Generator[count];
            Arrays.fill(gens, gen);
            return Generator.tuple(gens).fmap(Arrays::asList);
        }).generate(random, size);
    }
}