Functional Reactive Programming (FRP) is a programming technique that I think hasn’t filtered down to the level of workaday programmers (like myself) but is well-regarded in the academic community.
Upside is that it could make writing Gtk and web applications much simpler.
Downside is that no one from the academic world has ever managed to explain FRP in a way that makes any sense to mere mortals. There are, as far as I can see, no good tutorials about FRP on the web, and by “good” I mean to exclude any that mention words like “composition”, “point-free”, “point-wise”, “denotational” or any other jargon like that.
Well, this one isn’t too bad … What I really need though are real, concrete, compilable examples.
The inimitable Daniel Bünzli, author of the OCaml FRP framework React wrote his own intro to FRP today, although I’m still not convinced I understand it.
So I’m going to learn it, and if I can, describe it to you in some forthcoming posts.
But what everyone agrees on are the basics: FRP is about putting the imperative programming concept of a “variable” on a sound theoretical basis. Let me explain …
In C you can declare a variable, like:
#define UP 1
#define DOWN 2
int mouse_button_state = UP;
and you can assign to that C variable over the course of your program:
void button_pressed (void)
mouse_button_state = DOWN;
The problem is that
mouse_button_state changes as time passes, but the variable itself doesn’t capture the past, present or future of the variable. Assigning a new value to the variable (a) doesn’t record the time that the variable changed, and (b) obliterates all previous states of the variable. The variable has no memory of what happened before.
 I’m using the word “problem” advisedly here. You and I might not think this is a problem at all. But FRP is going to persuade us that this is a problem and by putting variables on a sounder theoretical basis, our programs will be shorter and easier to reason about.
C programs that really deal with mouse events are, of course, full of callbacks. When a mouse button changes state (or more often, when it changes state several times) we want to call back some function that takes an action in response to user input. Callbacks are a huge problem in imperative programs, as you’ll know if you’ve ever done anything non-trivial. Amongst the problems are (1) they run asynchronously, (2) they run in some other part of the program and it’s not obvious what runs when and where, and (3) they often have bad interactions when several callbacks run and they might be called in different orders.
FRP promises to fix this, again by modeling events on a sound theoretical basis.
FRP also promises to save us from reasoning about: complicated multithreaded programs, event-driven programs (like operating systems, libvirt, etc.), writing web applications, and writing GUI applications.
I’m yet to be convinced, but I’m going to learn about FRP and try to write the world’s first usable FRP tutorial.