zerologiko
zerologiko

Reputation: 2111

Javascript functional composition/sequencing

I'm trying to understand composition and "sequencing" concept in Javascript with an exercise:

Def. "composition" compose(f,g)(x) = f(g(x))

Def. "sequencing" sequence(f,g)(x) = g(f(x)) for more args sequence(f,g)(...args) = g(f(...args))

const sequence2 = (f1, f2) => (...args) => f2( f1(...args) );
const sequence = (f1, ...fRest) => fRest.reduce(sequence2, f1);

const f1 = (a, b) => {
    console.log(`[f1] working on: ${a} and ${b}`);
    return a + b;
}

const f2 = a => `Result is ${a}`;

const sequenceResult = sequence(f1, f1, f2)(1, 2, 5);
console.log(sequenceResult);

The console shows:

[f1] working on: 1 and 2
[f1] working on: 3 and undefined
Result is NaN

It seems that the second function in the sequence can't access the args: there is something I'm missing or it's the wrong approach for dealing with parameters? (The sequence function works for functions without params).

Here the JSFiddle

Upvotes: 0

Views: 88

Answers (2)

user5536315
user5536315

Reputation:

Functions only return a single value. There are two ways to augment functions by multiple return values:

  • return an array like tuple
  • instead of returning call a continuation

Here is a fun implementation for the latter, which is explicitly not meant for any production code:

const pipek = g => f => x => y => k =>
  k(g(x) (y) (f));

const addk = x => y => k =>
  (console.log("apply addk to", x, y), k(x + y));

const main = pipek(addk)
  (addk)
    (2)
      (3)
        (k => k(4)); // we have to pass the 4th argument within the continuation

console.log(main(x => x)); // escape from the continuation

Please note that all functions are curried and that I used the term pipe, which is the usual term for reverse function composition in JS.

Upvotes: 1

Bergi
Bergi

Reputation: 665536

It seems that the second function in the sequence can't access the args

Yes, that's normal and expected. According to the definition you gave,

sequence(f1, f1, f2)(1, 2, 5);

is equivalent to

f2(f1(f1(1, 2, 5)));

Of course neither f2 nor the outer f1 can access the arguments that are passed to the inner f1.

Upvotes: 1

Related Questions