module React:Declarative events and signals.sig
..end
React is a module for functional reactive programming (frp). It provides support to program with time varying values : declarative events and signals. React doesn't define any primitive event or signal, this lets the client choose the concrete timeline.
Consult the semantics, the basics and examples. Open the module to use it, this defines only two types and modules in your scope.
Release 0.9.4 - Daniel Bünzli <daniel.buenzli at erratique.ch>
type 'a
event
'a
.type 'a
signal
'a
.module E:sig
..end
module S:sig
..end
The following notations are used to give precise meaning to the combinators. It is important to note that in these semantic descriptions the origin of time t = 0 is always fixed at the time at which the combinator creates the event or the signal and the semantics of the dependents is evaluated relative to this timeline.
We use dt to denote an infinitesimal amount of time.
Events
An event is a value with discrete occurrences over time.
The semantic function [] : 'a event -> time -> 'a option
gives
meaning to an event e
by mapping it to a function of time
[e
] returning Some v
whenever the event occurs with value
v
and None
otherwise. We write [e
]t the evaluation of
this semantic function at time t.
As a shortcut notation we also define []<t : 'a event -> 'a option
(resp. []<=t) to denote the last occurrence, if any, of an
event before (resp. before or at) t
. More precisely :
e
]<t =
[e
]t' with t' the greatest t' < t
(resp. <=
) such that
[e
]t' <> None
.e
]<t = None
if there is no such t'.
Signals
A signal is a value that varies continuously over time. In contrast to events which occur at specific point in time, a signal has a value at every point in time.
The semantic function [] : 'a signal -> time -> 'a
gives
meaning to a signal s
by mapping it to a function of time
[s
] that returns its value at a given time. We write [s
]t
the evaluation of this semantic function at time t.
Equality
Most signal combinators have an optional eq
parameter that
defaults to structural equality. eq
specifies the equality
function used to detect changes in the value of the resulting
signal. This function is needed for the efficient update of
signals and to deal correctly with signals that perform
side effects.
Given an equality function on a type the combinators can be automatically
specialized via a functor.
Continuity
Ultimately signal updates depend on primitive updates. Thus a signal can only approximate a real continuous signal. The accuracy of the approximation depends on the variation rate of the real signal and the primitive's update frequency.
Basics
Primitive events and signals
React doesn't define primitive events and signals, they must be created and updated by the client.
Primitive events are created with React.E.create
. This function
returns a new event and an update function that generates an
occurrence for the event at the time it is called. The following
code creates a primitive integer event x
and generates three
occurrences with value 1
, 2
, 3
. Those occurrences are printed
on stdout by the effectful event pr_x
. open React;;
Primitive signals are created with
let x, send_x = E.create ()
let pr_x = E.map print_int x
let () = List.iter send_x [1; 2; 3]React.S.create
. This function
returns a new signal and an update function that sets the signal's value
at the time it is called. The following code creates an
integer signal x
initially set to 1
and updates it three time with
values 2
, 2
, 3
. The signal's values are printed on stdout by the
effectful signal pr_x
. Note that only updates that change
the signal's value are printed, hence the program prints 123
, not 1223
.
See the discussion on
side effects for more details.
open React;;
The clock example shows how a realtime time
flow can be defined.
let x, set_x = S.create 1
let pr_x = S.map print_int x
let () = List.iter set_x [2; 2; 3]
The update cycle and thread safety
Primitives are the only mean to drive the reactive system and they are entirely under the control of the client. When the client invokes a primitive's update function, React performs an update cycle. The update cycle automatically updates events and signals that transitively depend on the updated primitive. The dependents of a signal are updated iff the signal's value changed according to its equality function.
To ensure correctness in the presence of threads, update cycles
must be executed in a critical section. Let uset(p
) be the set
of events and signals that need to be updated whenever the
primitive p
is updated. Updating two primitives p
and p'
concurrently is only allowed if uset(p
) and uset(p'
) are
disjoint. Otherwise the updates must be properly serialized.
Below updates to x
and y
must be serialized, but z can
be updated concurently to both x
and y
.
open React;;
let x, set_x = S.create 0
let y, send_y = E.create ()
let z, set_z = S.create 0
let max_xy = S.l2 (fun x y -> if x > y then x else y) x (S.hold 0 y)
let succ_z = S.map succ zSimultaneous events
Update cycles are made under a synchrony hypothesis : the update cycle takes no time, it is instantenous.
Two event occurrences are simultaneous if they occur in the same update cycle; in other words if there exists a primitive on which they both depend. By definition a primitive doesn't depend on any primitive it is therefore impossible for two primitive events to occur simultaneously.
In the code below w
, x
and y
will have simultaneous occurrences while
z
will never have simultaneous occurrences with them.
let w, send_w = E.create ()
let x = E.map succ w
let y = E.map succ x
let z, send_z = E.create ()Side effects
Effectful events and signals perform their side effect exactly once in each update cycle in which there is an update of at least one of the event or signal it depends on.
Remember that a signal updates in a cycle iff its equality function determined that the signal value changed. Signal initialization is unconditionally considered as an update.
It is important to keep references on effectful events and
signals. Otherwise they may be reclaimed by the garbage collector.
The following program prints only a 1
.
let x, set_x = S.create 1
let () = ignore (S.map print_int x)
let () = Gc.full_major (); List.iter set_x [2; 2; 3]Lifting
Lifting transforms a regular function to make it act on signals.
The combinators
React.S.const
and React.S.app
allow to lift functions of arbitrary arity n,
but this involves the inefficient creation of n-1 intermediary
closure signals. The fixed arity lifting
functions are more efficient. For example :
let f x y = x mod y
Besides, some of
let fl x y = S.app (S.app ~eq:(==) (S.const f) x) y (* inefficient *)
let fl' x y = S.l2 f x y (* efficient *)
Pervasives
's functions and operators are
already lifted and availables in submodules of React.S
. They can be
be opened in specific scopes. For example if you are dealing with
float signals you can open React.S.Float
.
open React
If you are using OCaml 3.12 or later you can also use the
open React.S.Float
let f t = sqrt t *. sin t (* f is defined on float signals *)
...
open Pervasives (* back to pervasives floats *)
let open
construct
let open React.S.Float in
let f t = sqrt t *. sin t in (* f is defined on float signals *)
...
Mutual and self reference
Mutual and self reference among time varying values occurs naturally in programs. However a mutually recursive definition of two signals in which both need the value of the other at time t to define their value at time t has no least fixed point. To break this tight loop one signal must depend on the value the other had at time t-dt where dt is an infinitesimal delay.
The fixed point combinators React.E.fix
and React.S.fix
allow to refer to
the value an event or signal had an infinitesimal amount of time
before. These fixed point combinators act on a function f
that takes
as argument the infinitesimally delayed event or signal that f
itself returns.
In the example below history s
returns a signal whose value
is the history of s
as a list.
let history ?(eq = ( = )) s =
When a program has infinitesimally delayed values a
primitive may trigger more than one update
cycle. For example if a signal
let push v = function
| [] -> [ v ]
| v' :: _ as l when eq v v' -> l
| l -> v :: l
in
let define h =
let h' = S.l2 push s h in
h', h'
in
S.fix [] defines
is infinitesimally delayed, then
its update in a cycle c
will trigger a new cycle c'
at the end
of the cycle in which the delayed signal of s
will have the value
s
had in c
. This means that the recursion occuring between a
signal (or event) and its infinitesimally delayed counterpart must
be well-founded otherwise this may trigger an infinite number
of update cycles, like in the following examples.
let start, send_start = E.create ()
For technical reasons, delayed events and signals (those given to
fixing functions) are not allowed to directly depend on each
other. Fixed point combinators will raise
let diverge =
let define e =
let e' = E.select [e; start] in
e', e'
in
E.fix define
let () = send_start () (* diverges *)
let diverge = (* diverges *)
let define s =
let s' = S.Int.succ s in
s', s'
in
S.fix 0 defineInvalid_argument
if
such dependencies are created. This limitation can be
circumvented by mapping these values with the identity.
Examples
Clock
The following program defines a primitive event seconds
holding
the UNIX time and occuring on every second. An effectful event
converts these occurences to local time and prints them on stdout
along with an
ANSI
escape sequence to control the cursor position.
let pr_time t =
let tm = Unix.localtime t in
Printf.printf "\x1B[8D%02d:%02d:%02d%!"
tm.Unix.tm_hour tm.Unix.tm_min tm.Unix.tm_sec
open React;;
let seconds, run =
let e, send = E.create () in
let run () =
while true do send (Unix.gettimeofday ()); Unix.sleep 1 done
in
e, run
let printer = E.map pr_time seconds
let () = run ()