Functional Programming, Reductio

Came across a slide deck via Reddit with an excellent point, cutting across the various functional programming diciplines:

Central to the thesis of FP is the notion of referential transparency.

Referential transparency leads to program compositionality.

// #1
X x = function();
R r1 = arbitrary(x);
R r2 = arbitrary(x);

// #2
R r1 = arbitrary(function());
R r2 = arbitrary(function());

If these two programs produce the same outcome then function is referentially transparent.

Well put. Back to the Reddit thread, functional programming and imperative programming are not a true dichotomy, but they one does need to mix carefully.

I find it most useful to build imperative programs on top a functional base, a foundation if you will. Taking the previous example, the function ‘arbitrary’ may not be a true function; it may modify persistent state, the values r1 and r2 being unequal. But building on top of the referentially transparent ‘function’, i can later refactor my program from #1 to #3:

// #3
void part1() {
R r1 = arbitrary(function()); /*...*/
}
void part2() {
R r2 = arbitrary(function()); /*...*/
}

And be able to rely on r1 and r2 being unchanged from their meaning in #1.

Referential transparency can be explained as the property that a function means the same thing every time you call it, no matter where or when you call it. That’s a very useful property to have in understanding and refactoring programs.

Join the Conversation

1 Comment

  1. I also find a mixed style appealing. I don’t see any reason why some parts of a program can be referentially transparent and not others. There are many useful ways to mix functional and non functional code.

    The implementation of a referentially transparent function can manipulate state internally for instance, such as stack data, so long as the caller is never exposed to these state changes. Even in C this is very common, in fact recommended.

    It seems to me that the case for pure functional programming is usually overstated. It mostly buys you lazy evaluation, but you can get that in other languages as long as you manage it explicitly.

Leave a comment

Leave a Reply to Brendan Miller Cancel reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.