Higher-order methods for collections

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):


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 " ")