Stream generators (original) (raw)

Remi Forax forax at univ-mlv.fr
Fri Nov 30 11:38:54 PST 2012


On 11/30/2012 06:51 PM, Brian Goetz wrote:

I think it would be beneficial for comparison to show a bit of their implementations. Here's iterate(seed, UnaryOperator): public static Stream iterate(final T seed, final UnaryOperator f) { Objects.requireNonNull(f); final InfiniteIterator iterator = new InfiniteIterator() { T t = null; @Override public T next() { return t = (t == null) ? seed : f.operate(t); } }; return stream(new StreamSource.ForIterator<>(iterator), StreamOpFlag.ISORDERED); } Not too difficult. But, the idea is to make things that are easy in the header of a for-loop to be easy as the source of a stream.

this doesn't work if seed is null.

If InfiniteIterator is defined like this: public interface InfiniteIterator extends Iterator { public default boolean hasNext() { return true; } }

then the code can be written like this: @SuppressWarnings("unchecked") public Iterator iterate(T seed, UnaryOperator op) { Objects.requireNonNull(f); Object[] array = new Object[] { seed }; InfiniteIterator iterator = () -> { Object value = array[0]; array[0] = op.operate(value); return (T)value; }; return stream(new StreamSource.ForIterator<>(iterator), StreamOpFlag.IS_ORDERED); }

repeat(n) in Scheme is about 10 characters. Yeah, well this is Java...

and the way iterators are defined is different. In Java there is no allocation if f does no allocation, this is not the case in Scheme.

Rémi



More information about the lambda-libs-spec-observers mailing list