我在Coursera上问过这个问题,但没有人回答,所以我来了。
这是关于 Scala 函数式编程原理类(class)的最后一个作业(字谜)。

如果函数subtract 返回一个无序的Occurrences,那么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)]

List 类型是有序的。相反,如果他们使用 Map(本来可以),那么这将不是问题。

10-06 11:25