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

Incorrect filter Implementation in Chapter 3.3 (Exercise: Stream Combinators) #252

Open
AleAndForCode opened this issue Sep 16, 2024 · 0 comments

Comments

@AleAndForCode
Copy link

In Chapter 3.3, Exercise: Stream Combinators, the provided implementation of the filter method for the Stream trait seems incorrect.

In the current implementation, the tail method doesn’t correctly apply the filtering logic. It simply calls stream.tail, which doesn’t skip non-matching elements, causing infinite recursion or incorrect results.

Current Implementation:

def filter(pred: A => Boolean): Stream[A] = {
  val self = this
  new Stream[A] {
    def head: A = {
      def loop(stream: Stream[A]): A =
        if pred(stream.head) then stream.head
        else loop(stream.tail)

      loop(self)
    }

    def tail: Stream[A] = {
      def loop(stream: Stream[A]): Stream[A] =
        if pred(stream.head) then stream.tail
        else loop(stream.tail)

      loop(self)
    }
  }
}

Suggested Fix:
The tail method should continue filtering the stream.

def tail: Stream[A] = {
  def loop(stream: Stream[A]): Stream[A] =
    if (pred(stream.head)) stream.tail.filter(pred)
    else loop(stream.tail)
  loop(self)
}

Thanks for the great book!

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