我在 Coursera 上问了这个问题,但没有人回复,所以我来到这里。 这是关于 Scala 函数式编程原理类(class)的最后一个作业(Anagrams)。
如果函数减法返回无序出现,AnagramsSuite 中的最后一个测试将会失败。
此外,函数 wordOccurrences 必须返回已排序的 Occurrences。
那么,为什么出现的顺序很重要?
// sentenceAnagrams passes the Test
def subtract(x: Occurrences, y: Occurrences): Occurrences = ((y
foldLeft x.toMap)((result, current) => {
result.updated(current._1, result(current._1)-current._2)
}) filter (_._2>0)).toList.sortWith(_._1<_._1)
// Without sortWith, the sentenceAnagrams will fail to get the right answer
def subtract(x: Occurrences, y: Occurrences): Occurrences = ((y
foldLeft x.toMap)((result, current) => {
result.updated(current._1, result(current._1)-current._2)
}) filter (_._2>0)).toList
最佳答案
因为它是 part of the definition :
/** `Occurrences` is a `List` of pairs of characters and positive integers saying
* how often the character appears.
* This list is sorted alphabetically w.r.t. to the character in each pair.
* All characters in the occurrence list are lowercase.
*
* Any list of pairs of lowercase characters and their frequency which is not sorted
* is **not** an occurrence list.
*
* Note: If the frequency of some character is zero, then that character should not be
* in the list.
*/
type Occurrences = List[(Char, Int)]
列表类型是有序的。如果他们使用 map (本来就可以),那么这将不是问题。
关于scala - 为什么顺序在事件中很重要? Coursera-Scala,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54937317/