关于合并:在Scala中合并流

Merging streams in scala

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

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

,如果任何流为空,该函数就会中断

1
2
3
4
5
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
}

有什么提示如何解决?


您可以使用scalaz中的交错:

1
2
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)

您也可以将两个Stream一起zip一起使用,这将截断较长的Stream,并将它们从元组中删除flatMap

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

尽管我不能说它的效率。

1
2
3
4
5
6
7
8
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
2
3
4
5
6
7
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)