首页 技术 正文
技术 2022年11月11日
0 收藏 550 点赞 3,776 浏览 1533 个字

The act of currying can be described as taking a multivariate function and turning it into a series of unary functions.

Let’s see an example:

const add = a => b=> a + b;
const inc = add(1);const res = inc(3) //

This is a very basic currying example.

We wrote a function ‘add’ take a param ‘a’ return a function which take param ‘b’, finally return a + b;

We can based on ‘add’ function to create another function ‘inc’. This approach is good for resuability. But there is one problem, because you cannot do:

add(1,3)

To solve the problem we need to write a ‘curry’ function, the basic idea is:

1. Check the passed in function, how many params it should takes, in our case ‘add’ function take 2 params.

2. ‘curry’ should return another function, inside function it should check, if length of params is the same as function’s params, in our case is:

add(1,3)

Then we invoke function immediately. (Using .call for immediately invoke)

3. Otherwise, we should still return a function with param partially applyied. (using .bind for partially apply)

function curry(fn) {
// The number of fn's params
// fn = (a, b) => a + b
// then length is 2
const arity = fn.length;
console.log(arity)
return function $curry(...args) {
console.log(args, args.length)
if (args.length < arity) {
// partially apply
// in case of add(1)(2)
return $curry.bind(null, ...args);
}
// immediately invoke
// in case of add(1,2)
return fn.call(null, ...args);
};
};const add = curry((a, b) => a + b);
const inc = add(1);
const res = inc(2) //

Arity describes the number of arguments a function receives. Depending on the number it receives, there are specific words to describe these functions.

A function that receives one is called a unary function.

A function that receives two arguments is called a binary,

three equals a ternary,

and four equals a quaternary,

so forth and so on.

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,020
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,513
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,359
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,142
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,772
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,850