Functional Programming in Scala

by Stephane Micheloud, November 2010

[Home]
[Back]

In this article we present several examples of functional programming (FP) in Scala. FP [TH4515 2.1] treats computation as the evaluation of mathematical functions and avoids state and mutable data.

Collection classes

Common operations on collection classes are filter, map and reduce.

  1. As a first example, the following Java code tests a predicate on a collection of geometric regions containing bouncing balls:

    public boolean canStartLineAt(float x, float y) {
        for (BallRegion region : mRegions) {
            if (region.canStartLineAt(x, y)) {
                return true;
            }
        }
        return false;
    }

    In Scala, one can express the above predicate test as an anonymous function and pass it to the appropriate method — exists in this case —:

    def canStartLineAt(x: Float, y: Float): Boolean =
      mRegions exists (_.canStartLineAt(x, y))
  2. In this second Java example we return the percentage of the filled surface based on the ratio between the total area of a collection of regions containing bouncing balls and the game board area.

    public float getPercentageFilled() {
        float total = 0f;
        for (int i = 0; i < mRegions.size(); i++) {
            BallRegion region = mRegions.get(i);
            total += region.getArea();
            Log.d("Balls", "total now " + total);
        }
        return 1f - (total / getArea());
    }

    In Scala we simply combine two higher-order functions (functions with function arguments) to perform the same operation:

    def getPercentageFilled: Float = {
      val total = mRegions map (_.getArea) reduceLeft (_ + _)
      1f - (total / getArea)
    }

References

  1. The Scala Language Specification (SLS), Version 2.8
    Martin Odersky, November 2010
  2. Programming Language Abstractions for Mobile Code
    Stéphane Micheloud, October 2009
    PhD Thesis Report, LAMP/EPFL.

About the Author

Stephane's Picture
Stéphane Micheloud is a senior software engineer. He holds a Ph.D in computer science from EPFL and a M.Sc in computer science from ETHZ. At EPFL he worked on distributed programming and advanced compiler techniques and participated for over six years to the Scala project. Previously he was professor in computer science at HES-SO // Valais in Sierre, Switzerland.
[Top]

Other Articles