2016-03-15 72 views
2

它应该检查一个Stream(that)是否是另一个(this)的前缀。Scala实现startsWith在流上

例如,Stream(1,2,3)startsWith Stream(1,2)将为true。

这是我的实现,但它总是返回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 
} 

回答

1

我不知道你的数据流是如何实现的,但如果一切都懒,我认为这个问题是在你的第二个案例:

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

应该

h() == h2() 

否则你比较两个unevaluate d函数

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 
+0

你打我吧,但我认为应该是h()== h2()=> – ddkr

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