gpt4 book ai didi

javascript - 'currying' 和 'composition' 在 Javascript 中是同一个概念吗?

转载 作者:可可西里 更新时间:2023-11-01 01:40:47 24 4
gpt4 key购买 nike

最近我在一本 Javascript 书中读到了函数组合,然后在一个网站上我看到有人将其称为柯里化(Currying)。

它们是同一个概念吗?

最佳答案

@Omarjmh 的回答很好,但在我看来,撰写示例对于学习者来说非常复杂

Are they the same concept?

没有。

首先,柯里化(Currying)是将一个接受多个参数的函数转换为一系列函数,每个函数接受一个参数。

// not curried
const add = (x,y) => x + y;
add(2,3); // => 5

// curried
const add = x => y => x + y;
add(2)(3); // => 5

请注意应用柯里化(Currying)函数的独特方式,一次一个参数。


其次,函数组合是将两个函数组合成一个,在应用时返回链接函数的结果。

const compose = f => g => x => f(g(x));

compose (x => x * 4) (x => x + 3) (2);
// (2 + 3) * 4
// => 20

这两个概念密切相关,因为它们可以很好地相互配合。通用函数组合适用于一元函数(接受一个参数的函数),柯里化(Currying)函数也只接受一个参数(每个应用程序)。

// curried add function
const add = x => y => y + x;

// curried multiplication function
const mult = x => y => y * x;

// create a composition
// notice we only apply 2 of comp's 3 parameters
// notice we only apply 1 of mult's 2 parameters
// notice we only apply 1 of add's 2 parameters
let add10ThenMultiplyBy3 = compose (mult(3)) (add(10));

// apply the composition to 4
add10ThenMultiplyBy3(4); //=> 42

// apply the composition to 5
add10ThenMultiplyBy3(5); //=> 45

关于javascript - 'currying' 和 'composition' 在 Javascript 中是同一个概念吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36273977/

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