Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!news.albasani.net!.POSTED!not-for-mail From: Sebastian Newsgroups: comp.lang.java.programmer Subject: Lazy primes with Java 8 (was Re: Java 8 Streams and Eratosthenes) Date: Mon, 10 Jun 2013 01:27:54 +0200 Organization: albasani.net Lines: 58 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-15; format=flowed Content-Transfer-Encoding: 7bit X-Trace: news.albasani.net f4QEoV3LMyBwVkBL08EevuRacC0V21XukJ0Y1/oqO2xtA66bb6Z4aPKVZg51BExTHrCE+HALsexJLYrCJQej8w== NNTP-Posting-Date: Sun, 9 Jun 2013 23:27:40 +0000 (UTC) Injection-Info: news.albasani.net; logging-data="ElYOJjKofkYViY13SAUzt/yA7I7m7WeUgQRuGswZe71UnNYtd3eWdfWG0+Beq2325D+EFAp5t5H676FlFD2s4J3hsi+pl58G8s9mGpk+rm03NIDn3dXG5ePAfidGqEDa"; mail-complaints-to="abuse@albasani.net" User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.2.15) Gecko/20110303 Thunderbird/3.1.9 In-Reply-To: Cancel-Lock: sha1:RQ5sGdhZ3y42BCTsI2/9uACit8A= Xref: csiph.com comp.lang.java.programmer:24347 Am 05.06.2013 22:43, schrieb Arved Sandstrom: > On 06/05/2013 04:44 AM, Sebastian wrote: [snip] >> > Me I wouldn't re-invent the wheel in this case. Implementing this type > of laziness is not that straightforward. > > And why not use interop between JVM languages? This way you leverage the > strengths. I usually have Java as the main language, but for some > functionality in some apps I use Scala. Maintainability goes up, for > starters, as does reliability and speed of development. > > It's all ultimately JVM bytecode. > > AHS > It's not everyone has a management who sees it this way. In our large project (we're talking several hundred developers and a really complicated build process), I don't see anyone advocating more complexity by adding another compiler and language. Anyway, it's turned out not to be too complicated in straight Java. One can simply extend a straightforward implementation of the usual cons-list with the following features, giving one a FilterableConsList: a) accept a Function to generate the elements in the tail in sequence b) accept a Supplier> to supply a tail c) accept a Predicate to filter out non-matching elements from the tail and make the implementation class LazyConsList lazy for the tail (but eager for the head). It's also easy to implement AbstractCollection by providing an iterator and make the thing streamable by providing a spliterator of unknown size. With that, the driver for generating the first 100 primes becomes: LazyConsList s = sieve(LazyConsList.newList(2, x -> x + 1)); s.stream().limit(100).forEach(x->System.out.print(x + " ")); where the interesting sieve() method is defined like this: private LazyConsList sieve(FilterableConsList s) { Integer p = s.head(); return cons(p, () -> sieve(s.tail().filter(x -> x % p != 0))); } Now I think that looks pretty neat (and almost exactly like the corresponding Scala code.) -- Sebastian