Thursday, March 13, 2014

Monadic Functional Reactive Programming

Reactive programming - programs that interact with the "outside world" - present a problem to the pure functional programmer: how to program in the traditional style in the absence of updateable state? But problems can also be opportunities, and in this case the opportunity is to rethink the problem from a different perspective. The result that ensues is "functional reactive programming", often abbreviated to FRP, originated by Conal Elliott and Paul Hudak.

The essence of FRP is to think declaratively, or in other words to think about how to make a mathematical model of the problem domain. The key insight is then to see that the functional world offers just the right set of abstractions to do this. A continuously varying quantity - such as the position of an object in an animation (or indeed in a robot world) - a given by a function from time to coordinates. Continuous quantities can trigger discrete events, for example when a position exceeds a certain value, and conversely events can trigger changes in continuous quantities - such as the rebound of a (simulated) billiard ball from a (simulated) cushion. So, FRP gives very general - and declarative - models of hybrid systems.

So far, so good. We have a very powerful model of a very general set of systems, but how is this to be implemented? We are in a functional language, so we can describe a naive implementation, but sadly that is desperately inefficient, and so the history of the last decade or so has been one of searching for sufficiently efficient implementations gained without losing too much of the original power and elegance of the framework. One approach is to make everything discrete, which is the approach of the Lustre language, but aiming to keep as close to true continuity as possible, at least as an abstraction, has proved to be more of a challenge. Elliott has provided a number of implementation ideas, as has Nilsson; the paper here provides a new approach in which a monadic interface is designed for FRP. 

Under the monadic approach, continuous behaviours are allowed to terminate (and also to begin) and so there is a natural sequencing operation between them. As well as giving a more familiar API to the programmer, the author claims that this allows a clean - i.e. declarative - yet efficient implementation of the system. While it is too early to give a definitive judgement on this - we should wait to see what the take-up is - it may be that finally FRP has come into its own with this work. If so, we can look forward to a whole set of new libraries for high-level reactive programming in interface design, graphics, web programming and more. Watch this space …

This review of Monadic Functional Reactive Programming, from the 2013 Haskell Symposium, was drafted for Computing Reviews, but too long for their liking. So, I have posted it here instead :-(

No comments:

Post a Comment