延遲計算

讓程序的計算髮生在真正使用到的時候,而不是提早計算好全部數據,由於有些場景下,並非全部數據都會用到(好比棋局遊戲,不必計算全部的步驟)ide

LazyList構造器的tail參數傳入的是一個方法,但該方法的執行只發生在須要的時候(這裏只是一個demo,並非效率最高的版本)this

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);
    }
}
相關文章
相關標籤/搜索