你可以这样做:
def groupStream[A, B](s: Stream[A])(isSeparator: A => Boolean)(group: Seq[A] => B): Stream[B] =
group(s.takeWhile(!isSeparator(_)).toList) #:: groupStream(s.dropWhile(!isSeparator(_)).drop(1))(isSeparator)(group)
或者,如果您想要一个更易于阅读但更详细的版本:
def groupStream[A, B](s: Stream[A])(isSeparator: A => Boolean)(group: Seq[A] => B): Stream[B] = {
def isNotSeparator(i: A): Boolean = ! isSeparator(i)
def doGroupStream(s: Stream[A]): Stream[B] =
group(s.takeWhile(isNotSeparator).toList) #:: doGroupStream(s.dropWhile(isNotSeparator).drop(1))
doGroupStream(s)
}
如果你想要 Stream 上的隐式方法,你也可以这样做
implicit class ImprovedStream[A](val s: Stream[A]) extends AnyVal {
def groupStream[B](isSeparator: A => Boolean)(group: Seq[A] => B): Stream[B] = {
def isNotSeparator(i: A): Boolean = ! isSeparator(i)
def doGroupStream(st: Stream[A]): Stream[B] =
group(st.takeWhile(isNotSeparator).toList) #:: doGroupStream(st.dropWhile(isNotSeparator).drop(1))
doGroupStream(s)
}
}
现在,使用您的示例:
val a = Stream("|" ,"A","d","a","m","|","J","o","h","n", "|", "M", "a", "r", "y", "|", "J", "o", "e")
val c = groupStream(a)(_ == "|")(_.mkString)
c.take(10).toList
// List[String] = List("", Adam, John, Mary, Joe, "", "", "", "", "")
使用隐式版本:
val c = groupStream(a)(_ == "|")(_.mkString)