【问题标题】:Scala unFlatMap斯卡拉 unFlatMap
【发布时间】:2016-01-31 10:02:10
【问题描述】:

我想执行类似 unFlatMap 的操作。假设我有流:

Stream("|","A","d","a","m","|","J","o","h","n", ...)

流可能是无限的。我想将其转换为:

Stream("Adam", "John", ...)

当然这只是例子。一般来说,我想对由分隔符分隔的元素执行一些操作,通用签名将是:

def unFlatMap[B](isSeparator:A => Boolean)(group:Seq[A] => B):TraversableOnce[B]

如何以干净和高效的方式做到这一点?

【问题讨论】:

  • 如果流是您的示例所具有的方式,则不需要isSeparatorhead 是你的分隔符(比如h)。使用.takeWhile(h!=) 组装该项目。重复(作为迭代器)
  • 你可以看看GroupWithIterator是如何在KollFlitz中实现的。你的操作是x.groupWith((a, b) => b != "|").map(_.mkString.stripMargin).toStream

标签: scala collections functional-programming


【解决方案1】:

你可以这样做:

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)

【讨论】:

    猜你喜欢
    • 2011-09-16
    • 2017-10-23
    • 1970-01-01
    • 2017-01-19
    • 2021-06-09
    • 2021-11-06
    • 2011-12-29
    • 2017-06-19
    • 2016-02-14
    相关资源
    最近更新 更多