scala - 为什么顺序在事件中很重要? Coursera-Scala

标签 scala

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

相关文章:

scala - Scala 2.8 集合库是 "the longest suicide note in history"的情况吗?

scala - 如何设置隐式转换以允许数字类型之间的算术?

scala - 在包对象中使用案例类时类型不匹配

scala - 在 Scala 中,我可以仅将某些文字隐式转换为我的自定义类型吗?

scala - 在 Spark SQL 中自动且优雅地展平 DataFrame

scala - 当存在同名本地成员时从外部范围访问值

scala - 如何在scala中将List [Any]转换为List(Int,Int)?

scala - 类型中的尾随逗号

scala - 来自kafka的spark Streaming如何指定轮询事件的截止时间

scala - 尝试安装 scala 时 Mac OS Mavericks 中出现 Homebrew 错误