2014-11-14 97 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)