为什么顺序在发生时很重要? Coursera-Scala

时间:2019-03-01 02:57:25

标签: scala

我在Coursera上问了这个问题,但是没有人回答,所以我来了。 这是有关Scala中的Functional Programming Principles课程的最后一项作业(摘要)。

如果函数减法返回无序出现,则AnagramsSuite中的最后一个测试将失败。

此外,还要求wordOccurrences函数应返回已排序的事件。

那么,为什么发生顺序很重要?

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

2 个答案:

答案 0 :(得分:5)

因为它是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(可能已经使用过),那么这将不是问题。

答案 1 :(得分:2)

让我更清楚地解释@Andy Hayden的答案。

出现的类型是列表。我们用它来从Map dictionaryByOccurrences中获取单词。

我们通过dictionaryByOccurrences(subsetOccurrences)得到有意义的单词。如果不对事件进行排序,则无法从字典中获取单词。例如,如果我们通过[('s', 1), ('c', 1), ('a', 2), ('l', 1)]获得了无序子集def combinations,则无法从scala中得到单词dictionaryByOccurrences,其中scala的键可能是[('a', 2), ('s', 1), ('c', 1), ('l', 1)]。这两个列表不相同。

实际上,dictionaryByOccurrences是错误的,如果不对事件进行排序,则字谜将具有不同的键。