cognitect-labs / transducers-js

Transducers for JavaScript
Apache License 2.0
1.6k stars 44 forks source link

Direction of functional composition with toFn? #22

Closed wcourtney closed 9 years ago

wcourtney commented 9 years ago

The function comp for functional composition is applied using reverse ordering when used with the toFn() function.

I would expect that comp(f,g) would result in a function f(g(x)), as confirmed in the example given for the function:

var inc = function(n) { return n + 1 };
var double = function(n) { return n * 2 };
var incDouble = t.comp(double, inc);
incDouble(3); // 8

However, looking at the toFn function, the doc example (and experimentation) provide a result as g(f(x)):

var arr = [0,1,2,3,4,5],
var apush = function(arr, x) { arr.push(x); return arr; },
var xf = t.comp(t.map(inc),t.filter(isEven));
arr.reduce(t.toFn(xf, apush), []); // [2,4,6]

Were the composition consistent with the first example, the expected result of composing the mapping of increment to the even values of the input array should always be an array of exclusively odd values. Instead, it appears that we are filtering the even values of the incremented input array, i.e. it looks more like we should expect from t.comp(t.filter(isEven), t.map(inc)).

dchelimsky commented 9 years ago

Your observation is correct. See "Defining Transformations With Transducers" on http://clojure.org/transducers for details.

wcourtney commented 9 years ago

Thanks for the confirmation. I found a more detailed explanation here in case anyone else seeing this is interested.