Functional Reactive – Programming



Functional Reactive – Programming

1 2


frp-presentation

My Functional Reactive Programming presentation in reveal.js

On Github noppanit / frp-presentation

Functional Reactive

Programming

@noppanit

History

Reactive Manifesto

How long do you think people will wait for a page to load?

2 seconds

Wait?

Really?

250 milliseconds

A bit more of the fundamental

asynchronous

function fetchData(callback) {   // get me data   callback(data);}fetchData(function(data) {   // do something with the data});

event driven programming

React to events
<input type="button" id="submitButton" value="Submit" />
jQuery('#submitButton').click(function() {<br>     // do some funky stuff});

Many ways to implement

IEnumerable

interface IEnumerable<T> {    IEnumerator<T> GetEnumerator();}interface IEnumerator<T> {    bool MoveNext();    T GetCurrent();}

What's wrong with this?

It's pull based

function fetchData() {    var products = getProducts();    for(var index = 0; index < products.size(); index++) {         // populate data          // data 1         // data 2         // data 3         // stuck    }}

IObservable

interface IObservable<T> {   void Subscribe(IObserver<T> observer);}
interface IObserver<T> {    void OnNext(T value);    void OnError();    void OnCompleted();}

Not interested?

Let's look at some code

simplest example

reactive programming
A = X + Y
> X = 10;10> Y = 10;10> A = X + Y;20> X = 20;> A20

Example jQuery

X = 22

Y = 33

A = X+Y = 55

function setA(){  // A=X+Y as integers
  var A = parseInt($('#X').text()) + parseInt($('#Y').text());
  $('#A').text( A );
}

setA();
$('#X,#Y').css('cursor','pointer').click(function(){
  // by reaction to a click: updates A and X or Y
  var obj = $(this);
  obj.text(parseInt(obj.text())+1);
  setA();
});

Knockout.js

X = 22

Y = 33

A = X+Y = 55

      var kockoutExample = function KockoutExample() {
        this.x = ko.observable(22);
        this.y = ko.observable(33);
        this.a = ko.computed(function() {
          return this.x() + this.y();
        }, this);

        this.clickX = function() {
          this.x(this.x() + 1);
        };

        this.clickY = function() {
          this.y(this.y() + 1);
        };
     }

        

Event Streams

bacon.js

X = 22

Y = 33

A = X+Y = 55

        var x = $("#X").asEventStream("click").map(1);
        var y = $("#Y").asEventStream("click").map(1);
        function sum(x, y) {
          return x + y;
        }
        var a = plus.merge(anotherPlus);