Search code examples
scalastreamfunctional-programmingstartswith

Scala implementation of startsWith on Streams


It should check if one Stream (that) is a prefix of another (this).

For instance, Stream(1,2,3) startsWith Stream(1,2) would be true.

This is my implementation, but it always returns false!

Can anyone please tell me why and maybe also post the correction?

def startsWith[B >: A](that: Stream[B]): Boolean = (this, that) match {
  case (_,Empty) => true
  case (Cons(h,t),Cons(h2,t2)) if h == h2 => t().startsWith(t2())
  case _ => false
}

Solution

  • I am not sure how your stream is implemented but if everything is lazy I think the problem is in your second case:

       case (Cons(h,t),Cons(h2,t2)) if h == h2 => t().startsWith(t2())
    

    should be

       h() == h2()
    

    otherwise you are comparing two unevaluated functions