Functional Scala: Introduction

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 …

About these ads

29 Responses to “Functional Scala: Introduction”

  1. Heiko Seeberger Says:

    Mario,

    Awesome! That’s exactly the kind of smooth introduction to functional programming Java/OO developers need. Please carry on!

    Heiko

    • Mario Gleichmann Says:

      Heiko,

      thanks for your kind and encouraging words!

      As i wrote – i was walking some blind alleys before i got it the right way. Now, I only try to give some of the joy and knowledge back ;o)

      Greetings

      Mario

  2. Mario Fusco Says:

    Hi Mario,

    I completely agree with Heiko. I am trying to help my colleagues in understanding FP and this exactly what I need. Actually I was preparing something similar for my course at university. I suppose I will steal some of your ideas :)

    I will look forward to read the next posts.

    Bye,
    Mario

    • Mario Gleichmann Says:

      Mario,

      again – thank you very much for your feedback!

      Hope you’re able to convince your colleagues that learning and ‘playing’ with ideas of FP may extend their solution space …

      As you’re looking forward to the next posts … you’re always welcome, as well as any questions, criticism or suggestions :o)

  3. Bill La Forge Says:

    very nice

  4. Robin Says:

    Nice post, looking forward to the next one!

    That example with fold doesn’t actually work in my scala 2.8 repl. This works:

    val sum = (1 to 10).foldLeft(0)(_ + _)

    Is fold scala 2.7? Is it possible to not have to specify the 0?

    • Mario Gleichmann Says:

      Robin,

      thanks for your kind words!

      The given fold example within the post (accepting two arguments) was a custom Function, since i haven’t introduced partial application and currying yet.

      Moreover – not to be pedantic – foldLeft isn’t a Function in the strict sense of FP. Its a method, defined on trait TraversableOnce … ;o)

      Greetings

      Mario

      • Robin Says:

        I see, thanks. In the meantime I discovered reduceLeft, where the (0) isn’t necessary.

      • Heiko Seeberger Says:

        Hehe, looking forward in pleasant anticipation to how you will explain the difference between method and functions in something like this:

        val numbers = List(1, 2, 3)
        numbers foreach println

        Not that’s it not possible, but … ;-)

      • Mario Gleichmann Says:

        Heiko,

        now you force me to explain eta expansion within another episode … ;o)

  5. Cristian Popovici Says:

    Hi Mario,

    Excelent article! Please continue with this subject as it will help a lot of folks struggeling to get into the functional scala world.

    Cheers,
    Cristian.

  6. Functional Scala: Functions « brain driven development Says:

    [...] based function application as the basic computation method of Functional Programming within the last episode, let’s start with what Dr. Erik Meijer* would call the bread and butter of Functional [...]

  7. Alex Says:

    Excellent article, thank you. Very readable and understandable. I like you you how you contrast the 2 programming styles, imperative way (which most of us are most likely coming from) then writing the functional way and explaining what and how we gain from this. I’m looking forward to reading the series!

  8. Stefan De Boey Says:

    Thanks, nice article, this is also the kind of stuff needed to get more developers to take a look at Scala. For most developers with some notion of FP this will be basic, but I’ve noticed that for a lot of Java-only developers this is something entirely new.
    Looking forward to the next post.

  9. Functional Scala: Functions as Objects as Functions « brain driven development Says:

    [...] features of Functional programming when compared to the paradigm of imperative programming in episode one. In an imperative, state changing world i always have to be aware in which order the statements get [...]

  10. basetta Says:

    Thanks, nice well written introduction. I will spread it among my colleagues. :)

  11. Functional Scala: Closures « brain driven development Says:

    [...] knowledge about the definition and some of the characteristics of common Functions within the first three episodes, let’s not waste any more time and take a look at another example of a [...]

  12. Earle Poitier Says:

    That is some inspirational stuff. Never knew that opinions could be this varied. Thanks for all the enthusiasm to offer such helpful information here.

  13. Great series about Functional Scala « techscouting through the news Says:

    [...] You will also find some ideas for ordinary Java programming if you are not a new language hopper. This series will be continued, here are links to the first four articles. Introduction [...]

  14. Jimmy Walker "Reverse Phone" Guy Says:

    I thought you would want to know that this website isn’t showing up right on my iphone. Cool site though!

  15. Liane Hidde Says:

    I so enjoyed every bit of this site and I’ve bookmarked your blog to keep up with the new topics you will post in the future.

  16. Maritza Steinhauser Says:

    Hello, I used to be researching the internet & I discovered your web site. Keep up the superb work.

  17. Paul@Quantisan Says:

    Mario,
    Thanks for this well thought out intro! I’ve been reading about Scala and FO for a few days but don’t seem to understand what the fuss is about. Nothing have ‘clicked’ yet for me still, but I’m feeling some sparks are tinkling.

  18. Functional Scala: Introduction Says:

    [...] most of the discussion and articles about Scala centered around its object oriented features so… [full post] Mario Gleichmann brain driven development developmentscala 0 0 0 [...]

  19. Functional Scala: Tinkerbell, Frogs and Lists « brain driven development Says:

    [...] version of a list type which allows for updating their content then? Again, we only need to look back at the very basic characteristics of functional programming: all values which ever exist are just [...]

  20. Mark Silberbauer Says:

    Thanks, great intro! Exactly the type of explanation of concepts I’ve been looking for.

    Add a Facebook Like or Google+ +1 button so that people who are not on WordPress can “like” it too.

  21. Jacek Laskowski Says:

    After ca 3 years while self-learning of functional programming in Clojure, I’m so glad I’ve run across your blog. I’m more interested in functional paradigm and learning Scala in-between makes the reading even better! Thanks! On to reading the next episodes.

  22. cc Says:

    Why do you lift a paragraph directly from the book “learn you a haskell for great good” without attributing it?

    “I failed to learn Haskell 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: Haskell is great and if you’re interested in programming you should really learn it even if it seems weird at first. Learning Haskell is much like learning to program for the first time — it’s fun!”
    http://learnyouahaskell.com/introduction#so-whats-haskell

  23. free business checks Says:

    Do you have a spam issue on this blog; I also am a blogger, and I was wanting
    to know your situation; we have created some nice methods
    and we are looking to exchange techniques with other folks, be
    sure to shoot me an e-mail if interested.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 42 other followers

%d bloggers like this: