Skip to content

Instantly share code, notes, and snippets.

@sawaken
Last active August 29, 2015 14:08
Show Gist options
  • Save sawaken/2889f8f98cd5a4c4b386 to your computer and use it in GitHub Desktop.
Save sawaken/2889f8f98cd5a4c4b386 to your computer and use it in GitHub Desktop.
One easy example of Reactive Programming.
#include <stdio.h>
#include <stdlib.h>
typedef struct ReactiveInt* ReactiveInt;
struct ReactiveInt
{
int n;
int (*operator)(int, int);
ReactiveInt left, right;
};
#define ReactiveNum(n) NewReactive((n), NULL, NULL, NULL)
#define ReactiveAdd(l, r) NewReactive(0, Add, (l), (r))
#define ReactiveSub(l, r) NewReactive(0, Sub, (l), (r))
#define ReactiveMul(l, r) NewReactive(0, Mul, (l), (r))
#define ReactiveDiv(l, r) NewReactive(0, Div, (l), (r))
int Add(int a, int b) { return a + b; }
int Sub(int a, int b) { return a - b; }
int Mul(int a, int b) { return a * b; }
int Div(int a, int b) { return a / b; }
ReactiveInt NewReactive(int n, int (*operator)(int, int), ReactiveInt left, ReactiveInt right)
{
ReactiveInt ri = malloc(sizeof(struct ReactiveInt));
ri->n = n;
ri->operator = operator;
ri->left = left;
ri->right = right;
return ri;
}
int PullValue(ReactiveInt a)
{
if (a->operator == NULL) {
return a->n;
} else {
return a->operator(PullValue(a->left), PullValue(a->right));
}
}
void SetReactiveNum(ReactiveInt a, int n)
{
a->n = n;
}
void main()
{
ReactiveInt a, b, c, d, e, f, g;
a = ReactiveNum(1); // a = 1
b = ReactiveNum(2); // b = 2
c = ReactiveNum(3); // c = 3
d = ReactiveNum(4); // d = 4
e = ReactiveAdd(a, b); // e = a + b
f = ReactiveSub(c, d); // f = c - d
g = ReactiveMul(e, f); // g = e * f
printf("%d\n", PullValue(g)); // print g
SetReactiveNum(a, 100); // a = 100
printf("%d\n", PullValue(g)); // print g
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment