Skip to content

Programming with water, it reacts!

Jean Hugues Robert edited this page Mar 19, 2014 · 14 revisions

DRAFT!

This blog post introduces the l8 water javascript library. It's a "reactive programming" solution, like cells in a spreadsheet. It is also a "functional reactive programming" solution because it provides a "fluid" API to build dataflow streams in a functional style, ie with lots of filter(), map(), reduce() and so on.

The documentation for "water sources" is here and the one for "fluids" is there

Factorial, procedural style

  function fact( n ){
    function recur( n, total ){
      if( n <= 1 )return 1;
      return recur( n - 1, total * n );
    }
    return recur( n, 1 );
  }
  console.log( fact( 170 ) );

Factorial, using water sources

    var fact = Water.define( function( input, output ){
      input( Water, function( v ){ return [ v, 1 ] }, [] );
      var fact_loop = Water( input, function( v ){
        var n = v[0], total = v[1];
        if( n <= 1 ){
          output( total );
        }else{
          return [ n - 1, n * total ];
        }
      });
      fact_loop( fact_loop );
    } );
    console.log( fact( 170 ) );

Factorial, using fluids

    var fact = Water.fluid.define( function( input ){ 
      return input
      .map( function( v ){ return [ v, 1 ]; } )
      .while( function( v ){ return v[0] > 1; } )
        .map( function( v ){
          var n = v[0], total = v[1];
          return [ n - 1, n * total ];
        })
      .end_while()
      .map( function( v ){ return v[1]; } );
    } );
    console.log( fact( 170 ) );