Home
### Higher-order methods for collections

Higher-order methods are methods of collections that use a function object to perform some operation on all elements of the collection.

The following higher-order methods work on all collections described here (strings, arrays, lists, StringBuilder, ArrayBuffer, ListBuffer):

- L.foreach(f) executes the function object for each element of L;
- L.exists(f) returns true if for some element e of L the function f(e) returns true;
- L.forall(f) returns true if for all elements e of L the function f(e) returns true;
- L.count(f) returns the number of elements e of L for which the function f(e) returns true;
- L.filter(f) returns a new collection (of the same type) consisting of those elements e of L for which the function f(e) returns true;
- L.filterNot(f) is the same as L.filter(e => !f(e)).
- L.map(f) returns a new collection containing the elements f(a), f(b),..., where a,b,... are the elements of L.
- L.sortWith(f) returns a new collection in sorted order. Sorting is done using f as the comparison function. f(a,b) takes two list elements and returns true if a should come before b in the sorted order.

Many operations on list that would normally use a for-loop can be written using foreach. For instance, we can compute the sum of all elements in a list like this:

scala> B res1: List[Int] = List(1, 2, 3) scala> var sum = 0 sum: Int = 0 scala> B.foreach(sum += _) scala> sum res2: Int = 6

Here we process words from a file:

scala> val words = Source.fromFile("words.txt").getLines().toList words = List(aa, aah, aahed, ...) scala> words filter (_ contains "issis") res1 = List(missis, missises, narcissism, narcissisms, narcissist, narcissists) scala> words count (_.length > 20) res2: Int = 3 scala> words exists (_ startsWith "kw") res3: Boolean = true

And as a final example, here is a (short) program to compute prime numbers:

val n = args(0).toInt val sqrtn = math.sqrt(n).toInt var s = (2 to n).toList while (s.head <= sqrtn) { print(s.head + " ") s = s.tail filter (_ % s.head != 0) } println(s mkString " ")