Stream generators
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<T> Stream<T> iterate(final T seed, final
> UnaryOperator<T> f) {
> Objects.requireNonNull(f);
> final InfiniteIterator<T> iterator = new InfiniteIterator<T>() {
> T t = null;
>
> @Override
> public T next() {
> return t = (t == null) ? seed : f.operate(t);
> }
> };
> return stream(new StreamSource.ForIterator<>(iterator),
> StreamOpFlag.IS_ORDERED);
> }
>
> 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<T> extends Iterator<T> {
public default boolean hasNext() {
return true;
}
}
then the code can be written like this:
@SuppressWarnings("unchecked")
public <T> Iterator<T> iterate(T seed, UnaryOperator<T> op) {
Objects.requireNonNull(f);
Object[] array = new Object[] { seed };
InfiniteIterator<T> 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