Scala映射和/或groupby函数

时间:2012-10-25 00:53:44

标签: scala map grouping

我是Scala的新手,我正试图找出一些scala语法。

所以我有一个字符串列表。

wordList: List[String] = List("this", "is", "a", "test")

我有一个函数返回一个对列表,其中包含每个单词的辅音和元音计数:

def countFunction(words: List[String]): List[(String, Int)]

所以,例如:

countFunction(List("test")) => List(('Consonants', 3), ('Vowels', 1))

我现在想要一个单词列表并按计数签名对它们进行分组:

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")

我想我需要使用GroupBy来执行此操作:

def mapFunction(words: List[String]): Map[List[(String, Int)], List[String]] = { 
    words.groupBy(F: (A) => K)
}

我已经阅读了Map.GroupBy的scala api,看到F代表鉴别器功能,K是你想要返回的键的类型。所以我尝试了这个:

    words.groupBy(countFunction => List[(String, Int)]

但是,scala不喜欢这种语法。我尝试查找groupBy的一些示例,似乎没有任何帮助我的用例。有什么想法吗?

2 个答案:

答案 0 :(得分:7)

根据您的描述,您的计数功能应该使用单词而不是单词列表。我会这样定义:

def countFunction(words: String): List[(String, Int)]

如果你这样做,你应该可以拨打words.groupBy(countFunction),这与:

相同
words.groupBy(word => countFunction(word))

如果您无法更改countFunction的签名,那么您应该能够像这样调用group:

words.groupBy(word => countFunction(List(word)))

答案 1 :(得分:0)

您不应将函数的返回类型放在调用中。编译器可以自己解决这个问题。你应该这样称呼它:

words.groupBy(countFunction)

如果不起作用,请发布您的countFunction实施。

<强>更新

我在REPL中对它进行了测试并且这有效(请注意我的countFunction与您的签名略有不同):

scala> def isVowel(c: Char) = "aeiou".contains(c)
isVowel: (c: Char)Boolean

scala> def isConsonant(c: Char) = ! isVowel(c)
isConsonant: (c: Char)Boolean

scala> def countFunction(s: String) = (('Consonants, s count isConsonant), ('Vowels, s count isVowel))
countFunction: (s: String)((Symbol, Int), (Symbol, Int))

scala> List("this", "is", "a", "test").groupBy(countFunction)
res1: scala.collection.immutable.Map[((Symbol, Int), (Symbol, Int)),List[java.lang.String]] = Map((('Consonants,0),('Vowels,1)) -> List(a), (('Consonants,1),('Vowels,1)) -> List(is), (('Consonants,3),('Vowels,1)) -> List(this, test))

可以包含传递给groupBy的函数的类型,但就像我说你不需要它一样。如果你想传递它,你可以这样做:

words.groupBy(countFunction: String => ((Symbol, Int), (Symbol, Int)))