gpt4 book ai didi

scala - 在 Scala 中实现 groupBy 方法的替代方法?

转载 作者:行者123 更新时间:2023-12-01 19:13:00 24 4
gpt4 key购买 nike

我提出了 groupBy 的实现:

object Whatever
{
def groupBy[T](in:Seq[T],p:T=>Boolean) : Map[Boolean,List[T]] = {
var result = Map[Boolean,List[T]]()
in.foreach(i => {
val res = p(i)
var existing = List[T]() // how else could I declare the reference here? If I write var existing = null I get a compile-time error.
if(result.contains(res))
existing = result(res)
else {
existing = List[T]()
}
existing ::= i
result += res -> existing
})
return result
}
}

但对我来说,它看起来不太 Scalish(这是我要找的词吗?)。您能否提出一些改进建议?

编辑:在我收到有关折叠的“提示”后,我以这种方式实现了它:

def groupFold[T](in:Seq[T],p:T=>Boolean):Map[Boolean,List[T]] = {
in.foldLeft(Map[Boolean,List[T]]()) ( (m,e) => {
val res = p(e)
m(res) = e :: m.getOrElse(res,Nil)
})
}

你觉得怎么样?

最佳答案

如果您想按谓词(即 T => Boolean 的函数)进行分组,那么您可能只想这样做:

in partition p

如果您确实想用它创建 map ,那么:

val (t, f) = in partition p
Map(true -> t, false -> f)

话又说回来,您可能只是想要练习。在这种情况下,折叠解决方案就可以了。

关于scala - 在 Scala 中实现 groupBy 方法的替代方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2142215/

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