How does Scala's groupBy identity work?

后端 未结 6 1051
天涯浪人
天涯浪人 2021-02-01 05:56

I was browsing around and found a question about grouping a String by it\'s characters, such as this:

The input:

\"aaabbbccccdd\"
         


        
6条回答
  •  南笙
    南笙 (楼主)
    2021-02-01 06:29

    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 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
      }
    

    So groupBy contains a map into which inserts chars return by identity function.

提交回复
热议问题