在scala中合并流

时间:2014-11-14 17:22:33

标签: scala merge stream

我需要帮助将两个流合并为一个。输出必须如下:

(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
}

有任何线索如何解决?

3 个答案:

答案 0 :(得分:2)

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 :(得分:2)

您还可以将zip两个Stream放在一起,这会将更长的StreamflatMap截断为元组:

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)

答案 2 :(得分:2)

您可以使用scalaz中的interleave:

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)