Navigate / search

Why I Study Functional Programming

For a while now I’ve been slowly writing a book about learning functional programming. I don’t know if it will ever see the light of day, that isn’t really the point. It’s more of an exercise to help me learn. I thought I might share the introduction here.

The Introduction
I became aware of computers and computer programming around the same time I became aware of the Rubik’s Cube. I was nine years old. The Cube awakened a love of puzzles that has stayed with me to this day. The computer was then and still is the ultimate puzzle.

The Rubik’s cube can be solved, there is an obviously right solution. That right solution is elegant, it looks beautiful. Thirty years on from the cube’s heyday someone solving it still attracts attention and it’s still thrilling to see the colours fall into place with the last few turns.

With a computer there is no right solution. There are endless problems to be solved and many solutions to every problem.

For the first few years of playing with computers the challenge was to get it to do anything at all. I wrote simple childish games. Some were fun to play, all were fun to write.

Then there was a Eureka moment. People do this for a living. I could do this for a living. I could get paid to write computer programs.

Studying programming in college was a joy. It was amazing to discuss programming with people who loved it as much as I did, and were often much better at it than I was.

I loved my first job. I wrote code on my first day, put code into production in my first week. I stayed late almost every night. It wasn’t work. It was as much fun as I had always hoped.

There have been many high points in my career, projects that I’m proud of, they are not surprisingly also the projects I most enjoyed working on.

There have also be been low points. Instead of getting to work at my hobby, I turned my hobby into work. I rarely get the same thrill from coding that I did as a 9 or 10 year old. I rarely get to delight in elegant solutions. I rarely get to build something just for the fun of building it.

I continue to write code in my spare time but the relentless emergence of new technologies, tools, frameworks and platforms has meant that even my play time has become work time, study time. I don’t study for fun, I study to keep up, and I mostly fail at that.

Functional Programming was something I added to the list of things I must learn about. It sat there dormant while other “more important” things bubbled to the top and stole my attention.

In 2012, at the Norwegian Developer Conference Vagif Abilov gave a beautiful presentation on a Functional approach to Conway’s Game of Life using F#.

Seeing his solution fall into place was like seeing the last few turns of a Rubik’s Cube. It was elegant, it was simple, it was right. For someone who was becoming increasingly disillusioned with programming, it was frankly moving.

You didn’t need to be a brilliant programmer with encyclopaedic knowledge of frameworks to understand what he was doing. My 10 year old self could have been dropped into that room and understood it all.

The voting system at NDC involves putting Green, Yellow or Red cards into a box indicating whether you thought the talk was Good, Average or Bad. As I registered my vote I noticed that the box was full of Green. I wasn’t the only one in the room who was impressed by what they saw.

I started learning F# and Functional Programming that evening and I haven’t stopped since.

One of those clever guys I talked programming with back in college recently described learning functional programming as “like learning to program all over again”.

He’s right, it is, but it’s even more fun second time around.

Richard Dalton
Kildare, Ireland
May 2014

Learning To Think Functionally : Readability

This entry is part 10 of 11 in the series Learning to think Functionally

I’m going to be a little unethical here and disclose an answer to Project Euler problem 6.

It’s one of the easier ones, but even still, if you haven’t done it, head on over and solve it now before reading any further. It’ll only take a few minutes.

Here’s the problem:

The sum of the squares of the first ten natural numbers is: 385
The square of the sum of the first ten natural numbers is: 3025

Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

Simple, right?

Here are a few C# functions that give us the answer we need.

        static int Square(int n)
        {
            return n*n;
        }

        static int SumOfSquares(int first, int count)
        {
            var total = 0;
            for (var i = first; i <= count; i++)
                total += Square(i);
            return total;
        }

        static int SquareOfSum(int first, int count)
        {
            var total = 0;
            for (var i = first; i <= count; i++)
                total += i;
            return Square(total);
        }

We get the solution to the problem by subtracting one from the other:

SquareOfSum(1,100) - SumOfSquares(1,100)

Or, we take a more functional approach to the whole problem and use LINQ:

        static int Square(int n)
        {
            return n*n;
        }

        static int SumOfSquares(int first, int count)
        {
            return Enumerable.Range(first, count).Select(Square).Sum();
        }

        static int SquareOfSum(int first, int count)
        {
            return Square(Enumerable.Range(first, count).Sum());
        }

And we get result just as before:

SquareOfSum(1,100) - SumOfSquares(1,100)

Those Enumerable ranges are cool. I think it’s easier to figure out what’s going on than with the imperative example. That said, while it’s better, I’ve never found the readability of LINQ to be anything special. It’s ok.

Let’s look at the same code in F#

let square x = x * x
let sumOfSquares range = range |> List.sumBy square
let squareOfSum range = range |> List.sum |> square

And we can get our answer as follows:

squareOfSum [1 .. 100] - sumOfSquares [1 .. 100]

I think that reads a little better. You need familiarity with the concept of ‘mapping’ a List. If you’re using the C#/LINQ example above you probably know all you need to know.

Take a look again at the SquareOfSum function in the LINQ example. Reading left to right we encounter the call to Square first even though it happens last. This is quite common in imperative languages when functions calls are nested within function calls.

In F# the Forward-Pipe operator (|>) gets around that problem quite neatly.

We can go further with the F# example.

Since all we’re doing with those ‘range’ values is piping them into a chain of functions, we can get rid of them entirely and simply compose sumOfSquares and squareOfSum directly from List.sum, List.map and square.

let square x = x * x
let sumOfSquares = List.map square >> List.sum
let squareOfSum = List.sum >> square
squareOfSum [1 .. 100] - sumOfSquares [1 .. 100]

Out sumOfSquares and squareOfSum functions are now “Point Free” in Functional Programming parlance.