Skip to content

[js] 第139天 说下你对柯里化函数(currying)的理解,它有什么运用场景? #1142

Open
@haizhilin2013

Description

@haizhilin2013
Collaborator

第139天 说下你对柯里化函数(currying)的理解,它有什么运用场景?

Activity

NicholasBaiYa

NicholasBaiYa commented on Sep 2, 2019

@NicholasBaiYa

函数柯里化指的是将能够接收多个参数的函数转化为接收单一参数的函数,并且返回接收余下参数且返回结果的新函数的技术。
eg:

const add = x => y => x + y
let add5 = add(5)
add5(5) // 10
add(1)(2) // 3
LinStan

LinStan commented on Sep 2, 2019

@LinStan

柯里化指的是将一个接受多个参数的函数转为一次只接受一个参数的函数,将已接受的参数保存起来,返回接受剩余参数的新函数,当传入参数个数之和等于被柯里化的原函数的参数个数,返回计算结果。
这样可以使得函数变成只接受一个参数,返回一个值的状态,降低了编程复杂性。

function curry (fn) {
  const ctx = this;
  function inner (...args) {
    if (args.length === fn.length) 
    {
        return fn.call(ctx, ...args);
    }
    return (...innerArgs) => inner.call(ctx, ...args, ...innerArgs);
  }
  return inner;
}
EmiyaYang

EmiyaYang commented on Sep 2, 2019

@EmiyaYang

Function.prototype.length 返回形参个数, 这个知识点我现在才知道?

mwangshuxin

mwangshuxin commented on Sep 3, 2019

@mwangshuxin

太菜了 之前我都木有了解过 😂

haizhilin2013

haizhilin2013 commented on Sep 3, 2019

@haizhilin2013
CollaboratorAuthor

@mwangshuxin 正好借此机会学习下

ustchcl

ustchcl commented on Mar 21, 2020

@ustchcl

柯里化指的是将一个接受多个参数的函数转为一次只接受一个参数的函数,将已接受的参数保存起来,返回接受剩余参数的新函数,当传入参数个数之和等于被柯里化的原函数的参数个数,返回计算结果。
这样可以使得函数变成只接受一个参数,返回一个值的状态,降低了编程复杂性。

function curry (fn) {
  const ctx = this;
  function inner (...args) {
    if (args.length === fn.length) 
    {
        return fn.call(ctx, ...args);
    }
    return (...innerArgs) => inner.call(ctx, ...args, ...innerArgs);
  }
  return inner;
}

不是降低复杂性哦. 最早Curry是为了解决多参数函数在lamda演算里面表达问题.
现在js里面使用主要是为了函数复用.

xiaoqiangz

xiaoqiangz commented on Jul 14, 2022

@xiaoqiangz

柯里化函数是将一个接收多个参数的函数变成接收单一参数的函数,并且返回接收余下参数且返回结果的新函数。
使用场景:避免每次调用重复传参。

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    jsJavaScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @haizhilin2013@ustchcl@xiaoqiangz@EmiyaYang@NicholasBaiYa

        Issue actions

          [js] 第139天 说下你对柯里化函数(currying)的理解,它有什么运用场景? · Issue #1142 · haizlin/fe-interview