zoukankan      html  css  js  c++  java
  • [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.

  • 相关阅读:
    科技部:中国131家独角兽企业 名单文字版
    Application_Start事件中用Timer做一个循环任务
    HttpRuntime.Cache再学习
    USB 3.0规范中译本 第10章 集线器,主机下行口以及设备上行口规范
    Vue.js 入门教程
    用python爬了自己的微信,原来好友都是这样的!
    小白到大神,Python 密集知识点汇总
    如何处理JS,css与smarty标签的冲突
    全新 Kali Linux 系统安装指南
    xshell连接centos与ubuntu
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10514147.html
Copyright © 2011-2022 走看看