Scala 的 groupBy 身份如何工作? [英] How does Scala's groupBy identity work?
问题描述
我在浏览时发现了一个关于按字符对 String
进行分组的问题,例如:
I was browsing around and found a question about grouping a String
by it's characters, such as this:
输入:
"aaabbbccccdd"
将产生以下输出:
"aaa"
"bbb"
"cccc"
"ddd"
我发现了这个建议:
val str = "aaabbbccccdd"[
val list = str.groupBy(identity).toList.sortBy(_._1).map(_._2)
这个identity
的家伙让我很好奇.我发现它是在 PreDef
像这样:
And this identity
fellow got me curious. I found out it is defined in PreDef
like this:
identity[A](x: A): A
所以基本上它会返回给定的任何东西,对吗?但这如何适用于对 groupBy
的调用?
So basically it returns whatever it is given, right? but how does that apply in the call to groupBy
?
如果这是一个基本问题,我很抱歉,只是函数式编程仍然让我有点纠结.请让我知道我是否可以提供任何信息以使这个问题更清楚
I'm sorry if this is a basic question, is just that functional programming is still tangling my brains a little. Please let me know if there's any information I can give to make this question clearer
推荐答案
要理解这一点,只需使用 -Xprint:typer
选项调用 scala repl:
To understand this just call scala repl with -Xprint:typer
option:
val res2: immutable.Map[Char,String] = augmentString(str).groupBy[Char]({
((x: Char) => identity[Char](x))
});
Scalac 将一个简单的 String
转换为 StringOps
,它是 TraversableLike
的子类,它有一个 groupBy
方法:
Scalac converts a simple String
into StringOps
with is a subclass of TraversableLike
which has a groupBy
method:
def groupBy[K](f: A => K): immutable.Map[K, Repr] = {
val m = mutable.Map.empty[K, Builder[A, Repr]]
for (elem <- this) {
val key = f(elem)
val bldr = m.getOrElseUpdate(key, newBuilder)
bldr += elem
}
val b = immutable.Map.newBuilder[K, Repr]
for ((k, v) <- m)
b += ((k, v.result))
b.result
}
因此 groupBy 包含一个映射,其中插入由标识函数返回的字符.
So groupBy contains a map into which inserts chars return by identity function.
这篇关于Scala 的 groupBy 身份如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!