1

Stream 上的内置 zip 函数似乎会在输入流对中最短的位置截断。我怎样才能实现这个功能:

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.
4

2 回答 2

2

You could use zipAll method to extend the shorter collection to the length of the longer. This method involves creation of many intermediate objects.

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
  }
}
于 2013-08-02T13:31:28.020 回答
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
于 2016-07-01T01:12:14.427 回答