Created
October 17, 2014 13:23
-
-
Save buzzdecafe/6e330039bc0ef25e1feb to your computer and use it in GitHub Desktop.
thinking about transducers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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