gpt4 book ai didi

Scala unFlatMap

转载 作者:行者123 更新时间:2023-12-04 02:16:27 25 4
gpt4 key购买 nike

我想执行类似 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com