Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Scala's groupBy identity work?

Tags:

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

The input:

"aaabbbccccdd" 

Would produce the following output:

"aaa" "bbb" "cccc" "ddd" 

and I found this suggestion:

val str = "aaabbbccccdd"[ val list = str.groupBy(identity).toList.sortBy(_._1).map(_._2) 

And this identity fellow got me curious. I found out it is defined in PreDef like this:

identity[A](x: A): A 

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

like image 458
Rodrigo Sasaki Avatar asked Oct 03 '13 18:10

Rodrigo Sasaki


1 Answers

This is your expression:

val list = str.groupBy(identity).toList.sortBy(_._1).map(_._2) 

Let's go item by function by function. The first one is groupBy, which will partition your String using the list of keys passed by the discriminator function, which in your case is identity. The discriminator function will be applied to each character in the screen and all characters that return the same result will be grouped together. If we want to separate the letter a from the rest we could use x => x == 'a' as our discriminator function. That would group your string chars into the return of this function (true or false) in map:

 Map(false -> bbbccccdd, true -> aaa) 

By using identity, which is a "nice" way to say x => x, we get a map where each character gets separated in map, in your case:

Map(c -> cccc, a -> aaa, d -> dd, b -> bbb) 

Then we convert the map to a list of tuples (char,String) with toList.

Order it by char with sortBy and just keep the String with the map getting your final result.

like image 163
Vinicius Miana Avatar answered Sep 18 '22 02:09

Vinicius Miana