Round 6: Collections and functions

(1 to 100).foldRight(0)(_+_)

—Taking the sum of 1, 2, … 100.

Learning objectives

In this round you will learn …

  • … to use collections and functions to structure your programs

  • … that collections enable one to organize existing objects into

    • sets (unordered collections of objects)

    • sequences (ordered, and hence indexed, collections of objects), and

    • maps (associations from one set of objects into another)

  • … that an iterator is an object that supplies an interface to iterate through the objects in a collection

  • … that an immutable object is fixed at creation and cannot be modified afterwards

  • … that a mutable object has an internal state that may be modified after creation

  • … the concepts of an anonymous function, a pure function, and a function with side effects

  • … that functional programming is a programming style that implements a computation by applying (pure) functions to immutable data

  • … that functions are immutable objects which can be passed around as data and used to construct new functions

  • … that each parameter to a function may be passed either

    • by value (by evaluating the parameter expression and passing the value to the function), or

    • by name (by enclosing the expression in a function object that is invoked each time the parameter is referenced in the function body)

  • … that a function is closed at creation by binding the free variables to variables in lexical scope

(Material that is marked with one or more asterisks (*) is good-to-know, but not critical to solving the exercises or passing the course.)

Collections and functions

As we have seen previously in Module I, programming with low-level data types and data structures (Int, Long, Double, fixed-length Array, and so forth) implemented either directly in hardware or in the Java Virtual Machine is tedious and not very productive. To become more efficient and productive programmers, in this round we return to study higher-level (software-defined) types and data structures implemented in the scala.collection package.

Our emphasis will be on functional programming style, where we manipulate collections by transforming them to new collections by means of applying functions to them.