summaryrefslogtreecommitdiff
path: root/src/main/java/au/id/zancanaro/javacheck/Generator.java
blob: 2d2e5563adc0f98711af2ef377e0de53eeb0ff1e (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
package au.id.zancanaro.javacheck;

import java.util.List;
import java.util.Random;
import java.util.function.Function;

public interface Generator<T> {
    RoseTree<T> generate(Random random, int size);

    static <T> Generator<T> pure(T value) {
        return (random, size) -> RoseTree.pure(value);
    }

    @SafeVarargs
    static <T> Generator<List<T>> tuple(Generator<T>... generators) {
        return (random, size) -> {
            @SuppressWarnings("unchecked")
            RoseTree<T>[] result = (RoseTree<T>[]) new RoseTree[generators.length];
            int index = 0;
            for (Generator<T> generator : generators) {
                result[index++] = generator.generate(random, size);
            }
            return RoseTree.zip(Function.identity(), result);
        };
    }

    static <T> Generator<List<T>> list(int count, Generator<T> gen) {
        return (random, size) -> {
            @SuppressWarnings("unchecked")
            RoseTree<T>[] result = (RoseTree<T>[]) new RoseTree[count];
            for (int i = 0; i < count; ++i) {
                result[i] = gen.generate(random, size);
            }
            return RoseTree.shrink(Function.identity(), result);
        };
    }

    default <R> Generator<R> map(Function<T, R> f) {
        return (random, size) -> this.generate(random, size).map(f);
    }

    default <R> Generator<R> flatMap(Function<T, Generator<R>> action) {
        return (random, size) -> RoseTree.join(this.generate(random, size).map(action).map(g -> g.generate(random, size)));
    }
}