Compose 更符合数学概念

Pipe, but in the other direction. (2 min. read)
从右向左组合 反方向的pipe
If pipe made sense, you already know compose. Instead of going left-to-right, we go right-to-left.
This returns 49 since we’re using pipe.
组成 管道,但在另一个方向(2分钟(阅读)
如果管道有意义,你已经知道了。我们不是从左到右,而是从右到左。
因为我们使用管道,所以返回49。

  1. import { pipe } from 'ramda';
  2. const doMath = pipe(
  3. // start here
  4. double, // 2 * 2 = 4
  5. square, // 16
  6. triple, // 48
  7. increment // 49
  8. );
  9. const result = doMath(2);
  10. console.log({ result });

But the same sequence with compose returns 162, since the order of operations have reversed.

  1. import { compose } from 'ramda';
  2. const doMath = compose(
  3. double, // 162
  4. square, // 81
  5. triple, // 9
  6. increment // 2 + 1 = 3
  7. // start here
  8. );
  9. const result = doMath(2);
  10. console.log({ result });

To get 49, like pipe, flip the sequence.

  1. import { compose } from 'ramda';
  2. const doMath = compose(
  3. increment, // 49
  4. triple, // 48
  5. square, // 16
  6. double // 2 * 2 = 4
  7. // start here
  8. );
  9. const result = doMath(2);
  10. console.log({ result });

构图反映了构图的数学形式——最里面的函数首先出现。
compose mirrors the mathematical form of composition–the innermost function goes first.

  1. increment(triple(square(double(x))));