nickcoxdotme
nickcoxdotme

Reputation: 6707

Scala List methods: `remove` and `sort`

I'm working out of "Programming in Scala (First Edition)", and I've gotten to some List methods. There are two methods it names that give me an error in the interactive shell: remove and sort. Here are the examples it gives:

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

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

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

When I try those in the console, I get errors that those methods aren't "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)

So I thought maybe I was using a newer version (since this book appears to be written a few years back), and I consulted the List documentation. Both methods appear to be there in version 2.7.7 (the newest I could find). As you can see, I'm running 2.11.1.

Did these methods get remove from the List API since 2.7.7, or am I using them wrong?

Upvotes: 2

Views: 651

Answers (1)

om-nom-nom
om-nom-nom

Reputation: 62835

In the darker times of scala 2.7 (it's more than four years ago!) your code would work just fine, but now, with 2.8+ you have to use different names for remove and sort:

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

There is also .sorted for default sorting

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

and .sortBy(x => ...) to sort with some preparation (it's like sorted with ephemeral map):

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

And remove was replaced with filterNot (though, I think remove is more convinient name, even if it makes you think that collection is mutable, which is tricked Ven in his answer):

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

There is also, .filter, which does the opposite:

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

It can be seen way more frequently in scala code.

Upvotes: 6

Related Questions