Scala map and/or groupby functions
Based on your description, your count function should take a word instead of a list of words. I would have defined it like this:
def countFunction(words: String): List[(String, Int)]
If you do that you should be able to call words.groupBy(countFunction)
, which is the same as:
words.groupBy(word => countFunction(word))
If you cannot change the signature of countFunction
, then you should be able to call group by like this:
words.groupBy(word => countFunction(List(word)))
Related videos on Youtube
user1772790
Updated on September 14, 2022Comments
-
user1772790 over 1 year
I am new to Scala and I am trying to figure out some scala syntax.
So I have a list of strings.
wordList: List[String] = List("this", "is", "a", "test")
I have a function that returns a list of pairs that contains consonants and vowels counts per word:
def countFunction(words: List[String]): List[(String, Int)]
So, for example:
countFunction(List("test")) => List(('Consonants', 3), ('Vowels', 1))
I now want to take a list of words and group them by count signatures:
def mapFunction(words: List[String]): Map[List[(String, Int)], List[String]] //using wordList from above mapFunction(wordList) => List(('Consonants', 3), ('Vowels', 1)) -> Seq("this", "test") List(('Consonants', 1), ('Vowels', 1)) -> Seq("is") List(('Consonants', 0), ('Vowels', 1)) -> Seq("a")
I'm thinking I need to use GroupBy to do this:
def mapFunction(words: List[String]): Map[List[(String, Int)], List[String]] = { words.groupBy(F: (A) => K) }
I've read the scala api for Map.GroupBy and see that F represents discriminator function and K is the type of keys you want returned. So I tried this:
words.groupBy(countFunction => List[(String, Int)]
However, scala doesn't like this syntax. I tried looking up some examples for groupBy and nothing seems to help me with my use case. Any ideas?