gpt4 book ai didi

javascript - compose 函数如何处理多个参数?

转载 作者:行者123 更新时间:2023-12-04 12:53:34 32 4
gpt4 key购买 nike

这是我需要改进的“撰写”功能:

const compose = (fns) => (...args) => fns.reduceRight((args, fn) => [fn(...args)], args)[0];
这是一个实际的实现:

const compose = (fns) => (...args) => fns.reduceRight((args, fn) => [fn(...args)], args)[0];

const fn = compose([
(x) => x - 8,
(x) => x ** 2,
(x, y) => (y > 0 ? x + 3 : x - 3),
]);

console.log(fn("3", 1)); // 1081
console.log(fn("3", -1)); // -8

这是我的导师提出的改进。
const compose = (fns) => (arg, ...restArgs) => fns.reduceRight((acc, func) => func(acc, ...restArgs), arg);
如果我们在第一次迭代时传递像 func(x, [y]) 这样的参数列表,我仍然不明白我们如何使函数与 [y] 的解压缩数组一起工作?

最佳答案

下面我们来分析一下compose改进了什么做

compose = (fns) =>
(arg, ...restArgs) =>
fns.reduceRight((acc, func) => func(acc, ...restArgs), arg);
当你喂 compose有了许多功能,你就回来了……一个功能。在你的情况下,你给它一个名字, fn .
这是什么 fn功能是什么样的?通过简单的替换,您可以将其视为:
(arg, ...restArgs) => fns.reduceRight((acc, func) => func(acc, ...restArgs), arg);
在哪里 fns === [(x) => x - 8, (x) => x ** 2, (x, y) => (y > 0 ? x + 3 : x - 3)] .
所以你可以喂这个函数 fn带有一些参数,这将与 (arg, ...restArgs) 进行“模式匹配” ;在您的示例中,当您调用 fn("3", 1) , arg"3"restArgs[1] (所以 ...restArgs 在逗号后扩展为 1,所以你看到 fn("3", 1) 减少到
fns.reduceRight((acc, func) => func(acc, 1), "3");
从这里你可以看到
  • 最右边的函数,(x, y) => (y > 0 ? x + 3 : x - 3)使用两个参数调用 "3" (acc 的初始值)和 1 ,
  • 结果将作为第一个参数传递给中间函数,随后调用 func ,
  • 等等,

  • 但关键是 func 的第二个参数,即 1 , 只被最右边的函数使用,而它被传递给 但忽略了通过其他两个功能!
    结论
    函数组合是一元函数之间的事情。将它与具有高于 1 的元数的函数一起使用会导致混淆。
    例如考虑这两个函数
    square = (x) => x**2;   // unary
    plus = (x,y) => x + y; // binary
    你能谱写它们吗?好吧,您可以将它们组合成这样的函数
    sum_and_square = (x,y) => square(plus(x,y));
    compose您在问题底部获得的功能会很顺利:
    sum_and_square = compose([square, plus]);
    但是,如果您的两个功能是这些呢?
    apply_twice = (f) => ((x) => f(f(x))); // still unary, technically
    plus = (x,y) => x + y; // still binary
    您的 compose行不通。
    即使,如果函数 plus被 curry ,例如如果它被定义为
    plus = (x) => (y) => x + y
    然后可以考虑将它们组合成一个函数,如下所示:
    f = (x,y) => apply_twice(plus(x))(y)
    可以预见地产生 f(3,4) === 10 .
    你可以得到它 f = compose([apply_twice, plus]) .
    美容改善
    此外,我建议进行“化妆品”更改:制作 compose接受 ...fns而不是 fns ,
    compose = (...fns)/* I've only added the three dots on this line */ =>
    (arg, ...restArgs) =>
    fns.reduceRight((acc, func) => func(acc, ...restArgs), arg);
    并且您可以在没有 groupint 的情况下调用它,将函数组合成一个数组,例如你会写 compose(apply_twice, plus)而不是 compose([apply_twice, plus]) .
    顺便说一句,有 lodash
    该库中有两个函数可以处理函数组合:
  • _.flow
  • _.flowRight ,别名为 _.compose lodash/fp
  • 关于javascript - compose 函数如何处理多个参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69297091/

    32 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com