Personal Log »

Just tell it what you want

I’m reading Functional Programming, Simplified by Alvin Alexander, which is intended to make the process of learning functional programming (FP) in Scala as simple as possible.

It is a bit too soon to recommend the book, and it is a 700+ pages commitment –I’m glad it is simplified–, but I’m happy with what I’ve been reading so far.

In the introductory chapters, where Alexander starts to define what is FP, he includes a quote attributed to experienced FP developers:

In FP we don’t tell the computer how to do things, we just tell it what we want.

The idea behind the quote is that, in imperative programming, the programmer tells the compiler step by step what to do, while in FP you are telling what is what you want to be done, without caring about the actual implementation.

Instead of reproducing the same example from the book, let’s take a look at this short piece of C code:

char *leters = "aababcbcdefba";
int count = 0;

for (int i = 0; i < 13; i++)
    if (leters[i] == 'a')
        count++;

In this example we are counting how many times the character ‘a’ appears on a string. Very straightforward, isn’t it?

Let’s see how we would do this in Scala using FP:

"aababcbcdefba".count(_ == 'a')

Do I really care how count is implemented? No, I don’t; all I want is to know how many times the character ‘a’ appears on that string, and I can trust that function to be correctly implemented.

Although the point Alexander was making was not explicitly about the quote itself, it really resonated with me because I’ve been thinking about something similar in the context of a compiler targeting limited CPUs like the Z80.

One of the common struggles of making games for 8-bit microcomputers using C and the SDCC compiler is that the compiler is not always very efficient generating Z80 code. And thinking about imperative programming, it makes sense that it is hard.

I suspect the real reason for SDCC not being at the same level as other modern compilers is more related to resources and limitations of the target architecture; for example the Z80 has less registers than a modern CPU, and writing an efficient register allocator is a big part of the problem.

Anyway, I was wondering if a compiler that implemented some limited functional programming language would have an easier job if instead of telling it how to do things, we just tell it what we want.

Would you like to discuss the post? You can send me an email!