2014-11-14 99 views
2

我需要幫助將兩個流合併爲一個流。輸出具有如下:在scala中合併流

(elem1list1#elem1list2, elem2list1#elem2list2...) 

和功能破裂,如果任何流將是空

def mergeStream(a: Stream[A], b: Stream[A]):Stream[A] = 
if (a.isEmpty || b.isEmpty) Nil 
else (a,b) match { 
case(x#::xs, y#::ys) => x#::y 
} 

任何線索如何解決呢?

回答

1

您還可以 s ^在一起,這將截斷長Stream,並flatMap出來的元組:

a.zip(b).flatMap { case (a, b) => Stream(a, b) } 

雖然我不能講它的工作效率。

scala> val a = Stream(1,2,3,4) 
a: scala.collection.immutable.Stream[Int] = Stream(1, ?) 

scala> val b = Stream.from(3) 
b: scala.collection.immutable.Stream[Int] = Stream(3, ?) 

scala> val c = a.zip(b).flatMap { case (a, b) => Stream(a, b) }.take(10).toList 
c: List[Int] = List(1, 3, 2, 4, 3, 5, 4, 6) 
1
def mergeStream(s1: Stream[Int], s2: Stream[Int]): Stream[Int] = (s1, s2) match { 
    case (x#::xs, y#::ys) => x #:: y #:: mergeStream(xs, ys) 
    case _ => Stream.empty 
} 

scala> mergeStream(Stream.from(1), Stream.from(100)).take(10).toList 
res0: List[Int] = List(1, 100, 2, 101, 3, 102, 4, 103, 5, 104) 
1

您可以從scalaz交錯使用:

scala> (Stream(1,2) interleave Stream.from(10)).take(10).force 
res1: scala.collection.immutable.Stream[Int] = Stream(1, 10, 2, 11, 12, 13, 14, 15, 16, 17)