jlongster / transducers.js

A small library for generalized transformation of data (inspired by Clojure's transducers)
BSD 2-Clause "Simplified" License
1.73k stars 54 forks source link

compose( f, g ) != f(g()) #12

Closed LarryBattle closed 9 years ago

LarryBattle commented 9 years ago

From this post it states this. compose(x(), y(), z())(val) into x(y(z(val))) However when I test this, the functions are called in reverse order. Here's a test.

compose-test.js

var transducers = require("./");
var assert = require("assert");
var map = transducers.map;
var into = transducers.into;
var compose = transducers.compose;

var x = into([],
  compose(
    map(function(x) {
      return "x(" + x + ")"
    }),
    map(function(x) {
      return "y(" + x + ")"
    }),
    map(function(x) {
      return "z(" + x + ")"
    })
  ), [1]);

assert.equal(x.join(""), "x(y(z(1)))");

output

assert.js:92
  throw new assert.AssertionError({
    ^
AssertionError: "z(y(x(1)))" == "x(y(z(1)))"

Shouldn't the test pass?

jlongster commented 9 years ago

You're right, it's the comment in the post that is wrong. It should have been compose(x, y, z) and not compose(x(), y(), z()). I fixed the post.

compose will return a function that, when passed a value, will call the functions right-to-left. But note that these transducers return a function that take a transformer, so while they are calling right-to-left, they just build up a final chain of transformers, and then they are executed left-to-right. So all transducers are executed left-to-right, in the order they are defined.