[Javascript] Understand Curry

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) // 4

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) // 3
复制代码

 

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.

 

posted @   Zhentiw  阅读(152)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2018-03-12 [HTML 5] More about ARIA Relationships
2018-03-12 [HTML5] aria-label & aria-labelledby
2018-03-12 [HTML5] Why ARIA?
2018-03-12 [React] How to use a setState Updater Function with a Reducer Pattern
2017-03-12 [Recompose] When nesting affects Style
2016-03-12 [RxJS] Refactoring CombineLatest to WithLatestFrom
点击右上角即可分享
微信分享提示