Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

函数柯里化 #88

Open
Twlig opened this issue Mar 30, 2022 · 1 comment
Open

函数柯里化 #88

Twlig opened this issue Mar 30, 2022 · 1 comment

Comments

@Twlig
Copy link
Owner

Twlig commented Mar 30, 2022

什么是函数柯里化

函数柯里化(curry)是函数式编程里面的概念。curry的概念很简单:只传递给函数一部分参数来调用它,让它返回一个函数去处理剩下的参数。

柯里化有什么作用

主要有3个作用: 参数复用提前返回延迟执行

我们来简单的解释一下: 参数复用:拿上面 f这个函数举例,只要传入一个参数 z,执行,计算结果就是 1 + 2 + z 的结果,1 和 2 这两个参数就直接可以复用了。

提前返回 和 延迟执行 也很好理解,因为每次调用函数时,它只接受一部分参数,并返回一个函数(提前返回),直到(延迟执行)传递所有参数为止。

function curry(fn, ...args) {
    return args.length >= fn.length ? fn(...args) : (..._args) => curry(fn, ...args, ..._args)
}

function add(a, b, c) {
    return a+b+c
}

const addC = curry(add, 1)(2)(3)   //6

原文链接:

@Twlig
Copy link
Owner Author

Twlig commented Apr 21, 2022

变长柯里化

function dynamicAdd() {
  return [...arguments].reduce((prev, curr) => {
    return prev + curr
  }, 0)
}
function curry(fn, ...args) {
    function curried(..._args) {
        return curry(fn, ...args, ..._args)
    }
    curried.toString = function() {
        return fn(...args)
    }
    return curried
}
var add = curry(dynamicAdd);
alert(add(1)(2)(3)(4)) // 10

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant