2012-10-25 99 views
3

我是新来的斯卡拉,我想弄清楚一些scala语法。斯卡拉地图和/或groupby函数

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

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斯卡拉API和看到,F表示鉴别功能和K是你想要返回键的类型。所以我试过这个:

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

但是,scala不喜欢这种语法。我试着查找一些groupBy的例子,似乎没有任何东西可以帮助我处理用例。有任何想法吗?

回答

7

根据您的描述,您的计数功能应采取一个单词,而不是单词的列表。我会这样定义它:

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

如果你这样做,你应该能够调用words.groupBy(countFunction),这是一样的:

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

如果你不能改变的countFunction签名,然后你应该可以这样称呼小组:

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

这很好。我创建了第二个函数,只需要一个单词。我现在的其他功能只是调用这个单个字符串函数。谢谢您的帮助。 – user1772790

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