-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating
Scala Functional Programming Patterns
By :
Scala provides sorted, sortBy and sortWith methods. We will take a quick look at them and then tackle an interesting memoization problem.
The sorted method uses natural ordering amongst the elements of the collection. Natural ordering well, seems natural.
For example, given the following numbers:
1, 11, 22, 2
The natural ordering would be:
1, 2, 11, 22
And the alphanumeric ordering would be:
1, 11, 2, 22
Alternatively, please see http://blog.codinghorror.com/sorting-for-humans-natural-sort-order/ for more on natural ordering.
Here is sorted in action:
scala> import scala.util.Random import scala.util.Random scala> val list = List.fill(10)(Random.nextInt(100)) list: List[Int] = List(5, 49, 37, 56, 54, 64, 9, 85, 76, 28) scala> list.sorted res0: List[Int] = List(5, 9, 28, 37, 49, 54, 56, 64, 76, 85)
This, of course, creates a new list as the original list is immutable.
This method sorts on an attribute of the compound type. For example, given a list of tuples:
scala...
Change the font size
Change margin width
Change background colour