Skip to content

Instantly share code, notes, and snippets.

@buzzdecafe
Created October 17, 2014 13:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save buzzdecafe/6e330039bc0ef25e1feb to your computer and use it in GitHub Desktop.
Save buzzdecafe/6e330039bc0ef25e1feb to your computer and use it in GitHub Desktop.
thinking about transducers
var R = require('ramda');
// cf. http://thecomputersarewinning.com/post/Transducers-Are-Fundamental/
function inc(n) {
return n + 1;
}
function meanReducer(acc, x) {
var newAcc = {};
newAcc.sum = acc.sum + x;
newAcc.count = inc(acc.count);
return newAcc;
};
console.log(R.reduce(meanReducer, {sum: 0, count: 0}, R.range(0, 10)));
// Let's try to make a transducer that will cause our mean-reducer to increment all of the inputs.
/*
(defn increment-transducer [f1]
(fn [result input] ;; A transducer returns a reducing fn.
(f1 result ;; That reducing fn will still call 'f1',
(inc input)))) ;; but only after it increments the input.
=> (reduce (increment-transducer mean-reducer)
{:sum 0 :count 0}
(range 10))
{:count 10, :sum 55}
*/
var incrementTransducer = function(f1) {
return function(acc, x) {
return f1(acc, inc(x));
};
};
console.log(R.reduce(incrementTransducer(meanReducer), {sum: 0, count: 0}, R.range(0, 10)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment