作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想执行类似 unFlatMap 的操作。假设我有流:
Stream("|","A","d","a","m","|","J","o","h","n", .. .)
流可以是无限的。我想将其转换为:
Stream("亚当", "约翰", ...)
当然这只是例子。一般来说,我想对由分隔符分隔的元素执行一些操作,通用签名将是:
def unFlatMap[B](isSeparator:A => Boolean)(group:Seq[A] => B):TraversableOnce[B]
如何以干净且内存高效的方式做到这一点?
最佳答案
你可以这样做:
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)
关于Scala unFlatMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33445122/
我想执行类似 unFlatMap 的操作。假设我有流: Stream("|","A","d","a","m","|","J","o","h","n", .. .) 流可以是无限的。我想将其转换为: S
我是一名优秀的程序员,十分优秀!