Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Iterator.unfoldRight() eagerly evaluates provided function #2754

Open
etsinko opened this issue Dec 6, 2023 · 0 comments
Open

Iterator.unfoldRight() eagerly evaluates provided function #2754

etsinko opened this issue Dec 6, 2023 · 0 comments

Comments

@etsinko
Copy link

etsinko commented Dec 6, 2023

I recently noticed that the returned iterator always evaluates supplied function. Even if the iterator.next() or iterator.hasNext() is never called.
Moreover, the iterator will eagerly preload next element on iterator.getNext() call.
Both of these issues could be avoided by wrapping nextVal in Lazy. So instead of this:

    static <T, U> Iterator<U> unfoldRight(T seed, Function<? super T, Option<Tuple2<? extends U, ? extends T>>> f) {
        Objects.requireNonNull(f, "the unfold iterating function is null");
        return new AbstractIterator<U>() {
            private Option<Tuple2<? extends U, ? extends T>> nextVal = f.apply(seed);

            @Override
            public boolean hasNext() {
                return nextVal.isDefined();
            }

            @Override
            public U getNext() {
                final U result = nextVal.get()._1;
                nextVal = f.apply(nextVal.get()._2);
                return result;
            }
        };
    }

the following can be used:

    static <T, U> Iterator<U> unfoldRight(T seed, Function<? super T, Option<Tuple2<? extends U, ? extends T>>> f) {
        Objects.requireNonNull(f, "the unfold iterating function is null");
        return new AbstractIterator<U>() {
            private Lazy<Option<Tuple2<? extends U, ? extends T>>> nextVal = Lazy.of(() -> f.apply(seed));

            @Override
            public boolean hasNext() {
                return nextVal.get().isDefined();
            }

            @Override
            public U getNext() {
                Tuple2<? extends U, ? extends T> tuple = nextVal.get().get();
                final U result = tuple._1;
                nextVal = Lazy.of(() -> f.apply(tuple._2));
                return result;
            }
        };
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant