October 28, 2010 — Mario Gleichmann

Welcome to the first part of a series of episodes about ‘Functional Scala’. While positioning itself as a so called object-functional language, most of the discussion and articles about Scala centered around its object oriented features so far. If you’re reading this, chances are you want to learn more about the functional side of Scala. Well, you’ve come to the right place.

The idea for the following episodes arose out of some talks i gave about ‘Functional Scala’. I decided to write and talk about it because I wanted to solidify my own knowledge about Functional Programming in general and about Scala in particular … and because I thought I could help some people new to Scala to learn its functional features from my perspective.

Not least, there were some critical discussions in the past whether Scala is rightfully characterized as a functional Language. For this to decide, we firstly have to be clear about the core ideas, you’ll regularly come across within widely accepted functional Languages, like Haskell. We’re going to see if and how they are offered in Scala and try to push them to its limits. So without any further ado, let’s enter the world of Functional Programming (FP) in Scala.

Functional Programming vs. Imperative Programming

If you’ve ever heard some people talking about the merits of Functional Programming, you’ve certainly wondered if all those incredible promises like simplicity, clarity and elegance (we are all looking for) are really reacheable when following this approach. Here’s a little qoute by David Pollak, the creator of a Web framework, called Lift. Seems that he’s finally a convinced functional programmer, initially coined by the paradigm of imperative programming, after entering the functional world:

But most importantly, Scala taught me to program and reason about programming

differently. I stopped thinking in terms of allocating buffers, structs, and objects, and of

changing those pieces of memory. Instead, I learned to think about most of my programs

as transforming input to output. This change in thinking has lead to lower defect rates,

more modular code, and more testable code

How can this be? Aren’t we taught that object orientation (with object oriented languages as typical representatives for imperative languages) is all we need to write modular, maintainable code? What are the critical characteristics that differentiates Functional Programming from Imperative Programming?

Maybe we can detect some of these esential features by contrasting the implementation for solving a simple task like summing up a sequence of integers, let’s say from 1 to 10. We will do so in an imperative style and a second time using a functional style. Since Scala is an object-functional language, we’re able to use it for demonstrating both solutions:

Imperative Style

var sum = 0 var i = 1 while( i <= 10 ){ sum = sum + i i = i + 1 }

If you look closely at this piece of code, changes are … that you’ll see nothing really noticeable. That’s mostly because i didn’t focus your attention to any specific topic. In addition to that, if you are used to code within an imperative language, there’s nothing unusual to that piece of code: there are two variables which get assigned to new values while running trough the loop – after we get out of the loop, variable sum will hold the end result – that’s pretty normal, isn’t it?

The proper assignment of (intermediate-) values to that variables is warranted by the proper alignment of statements, that define the calculation of values and kind of instruct the correct order of value assignment. If you would swap line 4 with line 5 you may wouldn’t end up with the desired result.

In essence, we could abstract over this simple example and state the following:

Imperative Programming is a programming paradigm that describes computation in terms of correctly ordered statements that change a programs state

The fact that you can change the state of a variable give rise to some more interesting consequences: imagine you would call the loop some more times without reseting the two variables. If so you couldn’t rely any longer on the variable sum to hold only the sum of the values 1 up to 10 (the value of sum would depend on how often you’ve called the loop, right?). So in order to understand the intention of this piece of code you have to follow the whole sequence of statements and variable assignments. It’s not possible to only look at a single line and understand its meaning without understanding it’s surrounding statements. Thats because you have to follow the flow of variable reassignment. And in order to properly follow the flow of variable assignment you have to rely on the order in which the statements gets executed.

So there are two main characteristics you should keep in mind when thinking about imperative programming: Imperative Programming stands for an instruction based style which is expressed by a sequence of single instructions that specify precisely how the computation should proceed. This instruction based style is mainly mandated by the computation method of variable (re-)assignment (with all the consequences coming with it).

Functional Style

Let’s look at the solution written in a functional style:

val sum = fold( 1 to 10, _ + _ )

Wow, only a one-liner! But isn’t this cheating? Isn’t this only the effect of abstracting the loop away into that method (or what?) called fold? We now could take a deeper look into fold, but for now you have to believe me that there’s no such loop inside it which is based on variable (re-)assignment (we will take a deeper look into folds at some later episode!). Nevertheless,there is some indirect ‘evidence’ that there is no variable (re-)assigment within this piece of code:

val vs. var

First of all, take a look at the declaration of variable sum. This time it is declared using keyword val, which defines sum as an immutable value that can’t be reassigned. If you would try to assign another value to sum, the compiler would complain about that (that’s the reason why we had to define sum and i as mutable variables within the imperative example, using the keyword var). In the functional example, think of sum as an alias name that can be used whenever you want to refer to the expression on the right side (or the value to which that expression evaluates).

So while Scala is an object-functional Hybrid, it has to serve both worlds. But if you travell on the functional side, you may only use values (like the stairway book states, a Functional Programmer would only use val, while using var is akin to blasphemy).

Functions

It turns out, that fold is a function which accepts two parameters: a Set of values to fold and another function (huh?) which tells in which way to fold that values. Does this mean, that if we would like to fold that values and receive their product instead of their sum, we could throw in another function, doing multiplication? Yep, exactly!

This simple example shows a core characteristic of functional programming (no, it’s THE characteristic of functional Programming): its based on applying functions to arguments in order to receive some desired values (like the sum of some integers). Until we take a deeper look at Functions and their characteristics you can think of a function in a mathematical sense:

A Function is a mapping that takes one or more arguments and produces a single result (typically by a function definition that specify how the result can by calculated solely in terms of its arguments).

What you see here is a very short definition for a function. But this rather simple definition allows for a really powerful computation method: you can compute arbitrary results simply by applying functions to appropriate arguments. Since these arguments may also be other functions, you can come up with some new and powerful abstractions (as we will see when experiencing so called Higher Order Functions). Now the core idea for computation has shifted from a series of instructions (which specify precisely how the computation should proceed) to Notation of expressions, based on functions and values. You no longer have to follow a plan of instructions in order to understand a computation but decompose such an expression into its single elements.

You may have missed a single but extremely important word within the above Definition: The result of a function is solely dependend by its arguments. No global variables, no side-effects. This is pretty much what you would also expect when looking at functions in a mathematical sense. Let’s take a look at a simple function definition:

val add = ( x: Int, y: Int ) => x + y

What we have here is a function definition which describes how to calculate a result in terms of the given (formal) parameters x and y. You may call these two parameters variables, but in mathematic those variables are always fixed values which are passed to the function when it is applied to some current values (the actual parameters during the function application). The same is true for Functions defined within a Functional Language – better said: the values to which a function is applied are simply values – nothing less but nothing more, and therefore immutable (while in an imperative language, a variable refers to a specific area within memory, which is occupied by a value)

Stateless vs. Stateful

We’ve seen, that the concept of a variable is only valid within the context of imperative languages, where the value of a variable may be changed different times. In a functional world (like in mathematic), there are only functions and values. A variable name is nothing more than an alias name for a certain expression which can’t be changed. It’s only another name you can use whenever you refer to that expression. If you want it – there are only constants, values and parameters.

Hence there is also no idea of an assignment operation within a functional language. And since there is no such thing like value (re-)assignment there can’t be any state in a purely functional program. Wow, no state? But there must be state!? There are Statefull Session Beans, the state pattern, … How can i ever implement such a thing like a counter if there’s no idea of state? Well, it turns out that in a functional world there are other mechanisms to handle the absence of state (and hence side effects), yet gives you also the possibility to handle counting in a functional style (as we will see) .

Now that we’ve seen those critical differences and have named some crucial ideas of the imperative world and the functional world, we’re ready for our final characterization of Functional Programming:

Functional programming is a programming paradigm that describes computation as the evaluation of mathematical functions avoiding state, mutual data and therefore side effects

Don’t be afraid

Don’t be afraid, we will come back to those ideas in greater detail and see how they manifest within Scala. This first episode just gave you some general backround and tried to motivate you for the ideas of functional Programming. We’ll see how far we can get with it using Scala.

Don’t be afraid if you are new to Scala or Functional Programming at all. I will start from zero from the next episode on … trying to demonstrate you some new ideas and problem solving concepts extending your toolbelt …

I failed to learn ‘Functional Scala’ approximately 2 times before finally grasping it because it all just seemed too weird to me and I didn’t get it. But then once it just “clicked” and after getting over that initial hurdle, it was pretty much smooth sailing. I guess what I’m trying to say is: Scala is also great for functional programming and if you’re interested in programming you should really learn it even if it seems weird at first. Learning ‘Functional Scala’ is much like learning to program for the first time — it’s fun!

It forces you to think differently … so come with me …