Scala List方法:`remove`和`sort`

时间:2014-06-16 15:00:01

标签: scala

我正在使用“Scala编程(第一版)”,我已经使用了一些List方法。它命名的两种方法在交互式shell中给我一个错误:删除和排序。以下是它给出的例子:

val thrill = "will" :: "fill" :: "until" :: Nil

thrill.sort((a, b) a.charAt(0).toLowerCase < b.charAt(0).toLowerCase)

thrill.remove(s => s.length == 4)

当我在控制台中尝试这些时,我得到的错误是这些方法不是“a member of List[String]”:

scala> util.Properties.versionString
res41: String = version 2.11.1

scala> val myList = "one" :: "two" :: "three" :: "four" :: Nil
myList: List[String] = List(one, two, three, four)

scala> myList.sort((a, b) => a.charAt(0).toLowerCase < b.charAt(0).toLowerCase)
<console>:9: error: value sort is not a member of List[String]
              myList.sort((a, b) => a.charAt(0).toLowerCase < b.charAt(0).toLowerCase)
                     ^

scala> thrill.remove(s => s.length == 5)
<console>:9: error: value remove is not a member of List[String]
              thrill.remove(s => s.length == 5)

所以我想也许我正在使用更新的版本(因为这本书似乎是几年前写的),我咨询了List documentation。这两种方法似乎都出现在2.7.7版本中(我能找到的最新版本)。如您所见,我正在运行2.11.1。

自2.7.7以来,这些方法是否已从List API中删除,或者我使用它们是错误的?

1 个答案:

答案 0 :(得分:6)

在scala 2.7的黑暗时代(已经超过四年了!)你的代码会运行得很好,但是现在,对于2.8+,你必须为removesort使用不同的名称:

import Character.{toLowerCase => lower}
myList.sortWith { case (a, b) => lower(a.charAt(0)) < lower(b.charAt(0)) }
// List(four, one, two, three)

还有.sorted用于默认排序

List(2, 5, 3).sorted
// res10: List[Int] = List(2, 3, 5)

和.sortBy(x =&gt; ...)进行一些准备排序(就像用短暂的地图排序一样):

val foo = List("ac", "aa", "ab")
foo.sortBy(x => x.charAt(1))
// res6: List[String] = List(aa, ab, ac)

删除被替换为filterNot(虽然,我认为删除更方便的名称,即使它让你认为该集合是可变的,这在他的答案中被欺骗Ven):

thrill.filterNot(s => s.length == 5)
// res9: List[String] = List(will, fill)

还有.filter,它的反面相反:

thrill.filter(s => s.length == 5)
// res11: List[String] = List(until)

在scala代码中可以更频繁地看到它。