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.