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

Stack overflow when joining stream of empty streams #330

Open
l1cache opened this issue Feb 2, 2018 · 2 comments
Open

Stack overflow when joining stream of empty streams #330

l1cache opened this issue Feb 2, 2018 · 2 comments
Assignees

Comments

@l1cache
Copy link
Contributor

l1cache commented Feb 2, 2018

    public void test() {
        Stream.join(nils());
    }

    Stream<Stream<Integer>> nils() {
        return Stream.cons(Stream.nil(), this::nils);
    }

This code produces StackOverflowError cause append function recursively evaluates all nil streams while looking for head.
I only came up with ugly looking while inside bind function which produces stream's head on constant stack.
Any ideas?

@l1cache
Copy link
Contributor Author

l1cache commented Feb 3, 2018

I could think of this solution, but it looks like huge overkill:


  public final <B> Stream<B> bind(final F<A, Stream<B>> f) {
    return foldRight2((h, t) -> {
      Stream<B> f1 = f.f(h);
      return Option.iif(!f1.isEmpty(), () -> f1.append(t));
    }, Stream.nil());
  }

  public final <B> B foldRight2(final F2<A, P1<B>, Option<B>> f, final B b) {
    return Option.somes(map((h, t) -> f.f(h, P.lazy(() -> t._1().foldRight2(f, b))))).orHead(() -> b);
  }

  public final <B> Stream<B> map(final F2<A, P1<Stream<A>>, B> f) {
    return isEmpty() ? nil() : cons(f.f(head(), tail()), () -> tail()._1().map(f));
  }

@jbgi
Copy link
Member

jbgi commented Feb 10, 2018

Yeah, there is a laziness issue with Stream: both head and tail should be part of a lazy thunk. Not only the tail. And then reduction to "weak head normal form" should be properly trampolined. I will work an a redesign shortly. I have worked on a prototype of such design in the past. Thanks for reporting the issue and providing a motivation to finish the work!

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

2 participants