Lazy lists?

Millies, Sebastian Sebastian.Millies at softwareag.com
Wed Oct 9 00:00:10 PDT 2013


Hello there,

now that we have infinite Streams, wouldn’t it be worthwhile to have a lazy list
implementation in the collection library? By Lazy list, I mean a list that
would be strict for the head and lazy for the tail in that it

a) could be based on a Function<T> to generate the elements in the tail
   in sequence (like Stream#iterate())
b) would accept a Supplier<LazyList<T>> to supply a tail (like Stream#generate())
c) would accept a Predicate<T> to filter out non-matching elements
   from the tail
d) would allow constant time access to the head.

It would stream() using a spliterator of unknown size.

With it, we could write code somewhat like this to generate the first 100 primes
by trial division (where cons is also a static factory methof of LazyList):

LazyList<Integer> s = sieve(LazyList.newList(2, x -> x + 1));
s.stream().limit(100).forEach(x->System.out.print(x + " "));

private LazyList <Integer> sieve(LazyList <Integer> s) {
  Integer p = s.head();
  return cons(p, () -> sieve(s.tail().filter(x -> x % p != 0)));
}

Which would be pretty neat. Any particular reason – now that we have
lambdas – that there are no lazy data structures in the library?


n  Sebastian

Software AG – Sitz/Registered office: Uhlandstraße 12, 64297 Darmstadt, Germany – Registergericht/Commercial register: Darmstadt HRB 1562 - Vorstand/Management Board: Karl-Heinz Streibich (Vorsitzender/Chairman), Dr. Wolfram Jost, Arnd Zinnhardt; - Aufsichtsratsvorsitzender/Chairman of the Supervisory Board: Dr. Andreas Bereczky - http://www.softwareag.com



More information about the lambda-dev mailing list