You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Compose函数自定义实现疑问:为何compose1报TypeError错误?

Why does my second compose implementation throw "Uncaught TypeError: f is not a function"?

Let's break down exactly why your compose1 fails while compose works perfectly—this all comes down to how reduce is being used in each version.

First, recap your code

Your working compose function:

const compose = (...fns) => fns.reduce((f,g) => (...args) => f(g(...args)));

Your broken compose1 function:

const compose1 = (...fns) => (...args) => fns.reduce((f,g) => f(g(...args)));

And your curried helper functions:

const multi = a => x => x*a;
const devide = a => x => x/a;
const add = a => x => x+a;

The core difference: What does reduce return at each step?

How compose works (the correct version)

In compose, the reduce runs immediately when you define the composite function—not when you call it later.

Each iteration of reduce returns a new function that chains the previous composite function with the next one. Let's walk through your example compose(add(6), multi(4), devide(5)):

  1. First iteration: f is add(6), g is multi(4). We return (...args) => add(6)(multi(4)(...args))—a function, not a value.
  2. Second iteration: f is that new function, g is devide(5). We return (...args) => [previous function](devide(5)(...args))—another function.

By the end of reduce, you have a single function that, when called with (5), will run add(6)(multi(4)(devide(5)(5)))—exactly the function pipeline you want.

How compose1 breaks (the incorrect version)

In compose1, the reduce doesn't run until you call the final composite function (with (5)). Worse, each iteration of reduce returns the result of executing the functions, not a new function.

Let's walk through compose1(add(6), multi(4), devide(5))(5):

  1. First iteration: f is add(6), g is multi(4). We calculate f(g(5)) → add(6)(multi(4)(5)) → add(6)(20) → 26. This is a number, not a function.
  2. Second iteration: Now f is 26 (the result from the first step), g is devide(5). We try to run f(g(5)) → 26(devide(5)(5)) → 26(1).

You can't call a number like it's a function—hence the Uncaught TypeError: f is not a function error.

Key takeaway

  • compose uses reduce to build a reusable function pipeline—every step returns a function that can be chained further.
  • compose1 uses reduce to compute a value immediately on call, but since the first step returns a non-function value, the next iteration crashes.

内容的提问来源于stack exchange,提问作者Luke

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:32:11