2013-08-02 60 views
1

Stream上的內置壓縮函數顯示爲在輸入流對中最短的一個截斷。我怎樣才能實現這個功能:將壓縮流投影到最長的流

def firstOrLongest[T](a : Stream[ T ], b : Stream[ T) : Stream[ T ] 
// resulting stream should have the property that: 
// while there are still elements of a, return (the corresponding element of) a 
// else return (the corresponding element of) b. 
+0

見的答案我的問題[這裏](http://stackoverflow.com/q/3015962/334519 )針對Haskell中類似問題的一些解決方案。 –

回答

2

你可以使用zipAll方法較短收集延伸到的長度越長。該方法涉及創建許多中間對象。

def firstOrLongest[T](a : Stream[T], b : Stream[T]) : Stream[T] = { 
    val oa = a.map{ e => Some(e): Option[T] } 
    val ob = b.map{ e => Some(e): Option[T] } 
    oa.zipAll(ob, None, None).collect{ 
    case (Some(e), _) => e 
    case (None, Some(e)) => e 
    } 
} 
1

Stream類有一個附加運算符,它完全符合你的要求。

你描述的狀態:

// while there are still elements of a, return (the corresponding element of) a 
// else return (the corresponding element of) b. 

在Scala中,這只是:

a ++ b