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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With