本文介绍了在Javascript中'currying'和'composition'是相同的概念吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我在Javascript书中读到了函数组合,然后在网站上我看到有人将其称为currying。

Recently I read about function composition in a Javascript book, and then on a website I saw someone reference it as currying.

它们是否是相同的概念?

推荐答案

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

@Omarjmh's answer is good but the compose example is overwhelmingly complex for a learner, in my opinion

否。

首先,currying正在将一个函数转换为一个函数序列,每个函数接受一个参数。

First, currying is translating a function that takes multiple arguments into a sequence of functions, each accepting one argument.

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

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

注意应用curried函数的独特方式,一次一个参数。

Notice the distinct way in which a curried function is applied, one argument at a time.

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

Second, function composition is the combination of two functions into one, that when applied, returns the result of the chained functions.

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

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






这两个概念密切相关彼此很好。通用函数组合使用一元函数(带有一个参数的函数)和curried函数也只接受一个参数(每个应用程序)。


The two concepts are closely related as they play well with one another. Generic function composition works with unary functions (functions that take one argument) and curried functions also only accept one argument (per application).

// 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'是相同的概念吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 07:50