为什么订单在发生时很重要? Coursera – 斯卡拉

前端之家收集整理的这篇文章主要介绍了为什么订单在发生时很重要? Coursera – 斯卡拉前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在Coursera上问了这个问题,但没有人回复,所以我来到这里.
这是关于 Scala功能编程原理课程的最后一个任务(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,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(就像它本来的那样),那么这不会是一个问题.

猜你在找的Scala相关文章