Andres Jaimes

A purely functional example using Scala

By Andres Jaimes

On this tutorial we’re going to explore the basics of purely functional programming using Scala. One of the principles with purely functional style, is that we have to define concepts in terms of functions.

The basics: Comparing a number

We’re going to create a simple function that lets us compare a number to a previously stored number in a purely functional way. For that, we can define the following function:

val isTwo = { x: Int => x == 2 }

The previous definition assigns a function to isTwo and will let us pass a parameter (x) to be compared against number 2, returning true if they’re equal and false otherwise. For example:

isTwo(2) // returns true
isTwo(3) // returns false

We can then generalize it by creating a isNumber function, which is going to let us make a comparison with other possible values:

def isNumber(n: Int) = { x: Int => x == n }

As we can see from the previous snippet, we’re now using the parameter n to define the number to which we’ll make future comparisons against. For example, we can now create an instance like this:

val isOne = isNumber(1) // n = 1

And then test it like this:

isOne(1) // x = 1, then returns true
isOne(2) // x = 2, then returns false

From this simple definition we can create a list of comparable numbers like this:

val list = List(isNumber(1), isNumber(2), isNumber(3))
list.map(f => f(1)) // returns List(true, false, false)

I hope this helps you understand the basics behind the purely functional programming style.
Happy coding.