在Streams上实现startsWith的Scala

时间:2016-03-15 17:48:59

标签: scala stream functional-programming startswith

它应该检查一个Stream(那个)是否是另一个(这个)的前缀。

例如,Stream(1,2,3)startsWith Stream(1,2)将成立。

这是我的实现,但它总是返回false!

任何人都可以告诉我为什么,也许也可以发布更正?

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
}

3 个答案:

答案 0 :(得分:1)

  stream1.zip(stream2).dropWhile { case (a,b) => a == b }.isEmpty

答案 1 :(得分:1)

我不确定你的流是如何实现的,但如果一切都很懒,我认为问题出在第二种情况:

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

应该是

   h() == h2()

否则你要比较两个未评估的函数

答案 2 :(得分:0)

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
相关问题