For the past two days I’ve been looking into reactive programming. Wikipedia defines it as follows:
Reactive programming is a programming paradigm oriented around data flows and the propagation of change. This means that it should be possible to express static or dynamic data flows with ease in the programming languages used, and that the underlying execution model will automatically propagate changes through the data flow.
But that sounds kind of abstract, to make it more clear, let’s look at a simple Javascript program:
function calculateSum(l) {
var sum = 0;
for(var i = 0; i < l.length; i++) {
sum += l[i];
}
return sum;
}
var l = [2, 3, 4, 5];
var sum = calculateSum(l);
print(sum);
This program will print 14. Alright. Now let’s change the list l a little bit and print sum again:
l[2] = 6;
print(sum);
We now turned the 4 in l into 6. But when we print sum the sum hasn’t changed. This will likely not be very surprising to you. To calculate a new sum, you have to execute the calculateSum function again. But wouldn’t it be convenient if this happens automatically?
In spreadsheets this is exactly what happens. Open up Excel or Google Docs and fill in some numbers:

Now, in the cell below type a formula: =SUM(A2:A5) and push enter:

The cell now shows the sum of the numbers you entered. So far, nothing surprising. Now let’s change the 4 in that list into a 6, just like in the Javascript program:

Hey, the cell containing the sum has changed with it! This is called reactive programming. The SUM(A2:A5) is not a one time calculation, but reacts to changes to its parameters and recalculates if required. I feel this is a very powerful concept that has recently become more popular.
Flapjax is a language that adds this type of behavior to Javascript. Microsoft has the reactive extensions to .NET (Rx) that makes it easier to deal with events using LINQ. LunaScript is a Javascript-like language, currently under development that brings this programming model to Ajax web applications (have a look at their demo video, it’s cool). Trellis is a Python module that adds reactive features to Python. And currently I’m also adding these features to mobl.
Tags: mobl, reactive programming
The spreadsheet example and LunaScript seem more declarative than Rx.NET. In Rx, the reaction to events is still imperative (IObserver.OnNext(v)), although it shouldn't be too hard to abstract that away in a GUI control.
Btw, that spreadsheet example is fairly easy to achieve in a lazy functional language using Löb's Theorem:
loeb :: Functor a => a (a x -> x) -> a x
loeb x = fmap (a -> a (loeb x)) x
s1 = [const 2, const 3, const 4, const 5, sum . init]
s2 = [const 2, const 3, const 6, const 5, sum . init]
test1 = loeb s1 — [2,3,4,5,14]
test2 = loeb s2 — [2,3,6,5,16]