让程序的计算发生在真正使用到的时候,而不是提前计算好所有数据,因为有些场景下,并不是所有数据都会用到(比如棋局游戏,没必要计算所有的步骤)

LazyList构造器的tail参数传入的是一个方法,但该方法的执行只发生在需要的时候(这里只是一个demo,并不是效率最高的版本)

public class LazyList<T> implements MyList<T> {
    final T head;

    final Supplier<MyList<T>> tail;

    public LazyList(T head, Supplier<MyList<T>> tail) {
        this.head = head;
        this.tail = tail;
    }

    public T head() {
        return head;
    }

    public MyList<T> tail() {
        return tail.get();
    }

    public MyList<T> filter(Predicate<T> p) {
        return isEmpty() ? this : p.test(head()) ? new LazyList<>(head(), () -> tail().filter(p)) : tail().filter(p);
    }

    @Override
    public boolean isEmpty() {
        return false;
    }
}

class Demo {
    public static LazyList<Integer> from(int n) {
        return new LazyList<Integer>(n, () -> from(n + 1));
    }

    public static MyList<Integer> primes(MyList<Integer> numbers) {
        return new LazyList<>(numbers.head(), () -> {
            return primes(numbers.tail().filter(n -> n % numbers.head() != 0));
        });
    }

    public static void main(String[] args) {
        LazyList<Integer> numbers = from(2);
        int two = primes(numbers).head();
        int three = primes(numbers).tail().head();
        int five = primes(numbers).tail().tail().head();
        System.out.println(two + " " + three + " " + five);
    }
}

矮人水枪手
29 声望3 粉丝

Ye have a target?