Home  >  Article  >  Web Front-end  >  How to implement the exquisite automatic currying function in JS

How to implement the exquisite automatic currying function in JS

小云云
小云云Original
2017-12-13 09:27:541226browse

This article gives you a detailed analysis of the exquisite automatic currying method in JS and analyzes the process and principles through code examples. Please refer to it and study it. I hope it can help you.

What is currying?

In computer science, currying is to transform a function that accepts multiple parameters into a function that accepts a single parameter (the first parameter of the original function), and returns the remaining parameters. The technique of a new function that takes arguments and returns a result. This technique was named by Christopher Strachey after logician Haskell Curry, although it was invented by Moses Schnfinkel and Gottlob Frege.

The theory seems overwhelming? It doesn’t matter, let’s take a look at the code first:

Curriization application

Suppose we need to implement a function that performs some processing on list elements, for example, let each element in the list add One, then it’s easy to think of:

const list = [0, 1, 2, 3];
list.map(elem => elem + 1);

It’s very simple, right? What if we want to add 2 more?

const list = [0, 1, 2, 3];
list.map(elem => elem + 1);
list.map(elem => elem + 2);

It seems that the efficiency is a bit low. Can the processing function be encapsulated?

But the callback function of map only accepts the current element elem as a parameter. It seems that there is no way to encapsulate it...

You may think: If you can get a partial configuration A good function is fine, for example:

// plus返回部分配置好的函数
const plus1 = plus(1);
const plus2 = plus(2);
plus1(5); // => 6
plus2(7); // => 9

Pass such a function into the map:

const list = [0, 1, 2, 3];
list.map(plus1); // => [1, 2, 3, 4]
list.map(plus2); // => [2, 3, 4, 5]

Isn’t it great? In this way, no matter how much you add, you only need list.map(plus(x)), which perfectly implements encapsulation and greatly improves readability!

But here comes the question: How to implement such a plus function?

This is where currying comes in handy:

currying function

// 原始的加法函数
function origPlus(a, b) {
 return a + b;
}
// 柯里化后的plus函数
function plus(a) {
 return function(b) {
  return a + b;
 }
}
// ES6写法
const plus = a => b => a + b;

You can see , the curried plus function first accepts a parameter a, and then returns a function that accepts a parameter b. Due to closure, the returned function can access the parameter a of the parent function, so for example: const plus2 = plus (2) can be equivalent to function plus2(b) { return 2 + b; }, thus achieving partial configuration.

In layman's terms, currying is a process of partially configuring a multi-parameter function, with each step returning a partially configured function that accepts a single parameter. In some extreme cases, you may need to partially configure a function many times, such as multiple additions:

multiPlus(1)(2)(3); // => 6

This way of writing seems strange, right? But if you fall into the big pit of functional programming in JS, this will be the norm.


Exquisite implementation of automatic currying in JS

Currying is a very important part of functional programming. Many functional languages ​​(eg. Haskell) automatically curry functions by default. However, JS does not do this, so we need to implement the automatic currying function ourselves.

First enter the code:

// ES5
function curry(fn) {
 function _c(restNum, argsList) {
  return restNum === 0 ?
   fn.apply(null, argsList) :
   function(x) {
    return _c(restNum - 1, argsList.concat(x));
   };
 }
 return _c(fn.length, []);
}
// ES6
const curry = fn => {
 const _c = (restNum, argsList) => restNum === 0 ?
  fn(...argsList) : x => _c(restNum - 1, [...argsList, x]);
 return _c(fn.length, []);
}
/***************** 使用 *********************/
var plus = curry(function(a, b) {
 return a + b;
});
// ES6
const plus = curry((a, b) => a + b);
plus(2)(4); // => 6

This achieves automatic currying!

If you can understand what happened, then congratulations! The boss everyone calls you is you! , please leave a like and start your functional career (funny

If you don’t understand what’s going on, don’t worry, I will help you sort out your ideas now.

Requirements Analysis

We need a curry function, which accepts a function to be curried as a parameter, returns a function for receiving a parameter, and puts the received parameters into a list. When the parameter When the number is sufficient, the original function is executed and the result is returned.

Implementation method

Simply thinking, we can know that the number of steps of the curried partial configuration function is equal to the number of parameters of fn. That is to say, the plus function with two parameters needs to be partially configured in two steps. The number of parameters of the function can be obtained through fn.length

The general idea is to put the parameter in every time a parameter is passed. In a parameter list argsList, if there are no parameters to be passed, then fn.apply(null, argsList) is called to execute the original function. To achieve this, we need an internal judgment function _c(restNum, argsList). ), the function accepts two parameters, one is the number of remaining parameters restNum, and the other is the list of obtained parameters argsList; the function of _c is to determine whether there are any parameters that have not been passed in. When restNum is zero, it is time to pass fn.apply(null, argsList) executes the original function and returns the result. If there are still parameters that need to be passed, that is, when restNum is not zero, a single-parameter function needs to be returned.

function(x) {
 return _c(restNum - 1, argsList.concat(x));
}

to continue receiving parameters. A tail recursion is formed here. After the function accepts a parameter, the number of remaining parameters restNum is reduced by one, and the new parameter x is added to argsList and passed to _c for recursion. Call. The result is that when the number of parameters is insufficient, the single-parameter function responsible for receiving new parameters is returned. When there are enough parameters, the original function is called and returned:

function curry(fn) {
 function _c(restNum, argsList) {
  return restNum === 0 ?
   fn.apply(null, argsList) :
   function(x) {
    return _c(restNum - 1, argsList.concat(x));
   };
 }
 return _c(fn.length, []); // 递归开始
}

Is it starting to become clearer?

The ES6 writing method looks much simpler due to the use of syntactic sugar such as array destructuring and arrow functions, but the idea is the same. Same~

// ES6
const curry = fn => {
 const _c = (restNum, argsList) => restNum === 0 ?
  fn(...argsList) : x => _c(restNum - 1, [...argsList, x]);

 return _c(fn.length, []);
}

Comparison with other methods


There is another commonly used method:

function curry(fn) {
 const len = fn.length;
 return function judge(...args1) {
  return args1.length >= len ?
  fn(...args1):
  function(...args2) {
   return judge(...[...args1, ...args2]);
  }
 }
}
// 使用箭头函数
const curry = fn => {
 const len = fn.length;
 const judge = (...args1) => args1.length >= len ?
  fn(...args1) : (...args2) => judge(...[...args1, ...args2]);
 return judge;
}

Compared with the method mentioned previously in this article, it is found that this method has two problems:

Relies on ES6 destructuring (the function parameter ...args1 and ...args2);

性能稍差一点。

性能问题

做个测试:

console.time("curry");
const plus = curry((a, b, c, d, e) => a + b + c + d + e);
plus(1)(2)(3)(4)(5);
console.timeEnd("curry");

在我的电脑(Manjaro Linux,Intel Xeon E5 2665,32GB DDR3 四通道1333Mhz,Node.js 9.2.0)上:

本篇提到的方法耗时约 0.325ms

其他方法的耗时约 0.345ms

差的这一点猜测是闭包的原因。由于闭包的访问比较耗性能,而这种方式形成了两个闭包:fn 和 len,前面提到的方法只形成了 fn 一个闭包,所以造成了这一微小的差距。

相关推荐:

详解JavaScript函数柯里化

js柯里化的实例详解

javascript中有趣的反柯里化深入分析_基础知识

The above is the detailed content of How to implement the exquisite automatic currying function in JS. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn