简体   繁体   English

ES6立即调用递归箭头函数

[英]ES6 immediately invoke recursive arrow function

This is my current code: 这是我目前的代码:

const fn = parameter => {
    // if, else ...
    fn(X);
};
fn(0);

Now, I can't use this approach as I need to call the function with a parameter and it must be callable recursively. 现在,我不能使用这种方法,因为我需要使用参数调用函数,并且它必须可递归地调用。

How to refactor the above arrow function to be immediately invoked and recursively callable? 如何重构上面的箭头函数,以便立即调用和递归调用?

First, let me put the disclaimer that Immediately-Invoked-Function-Expressions (IIFE) are considered bad practice in ES6, and this is tail-recursion and personally I would change it to a for loop. 首先,让我把免责声明立即调用函数表达式(IIFE) 视为 ES6中的不良实践 ,这是尾递归,我个人将其更改为for循环。

but you can always do this I guess: 但你总能这样做我猜:

((x) =>{ const fn=(p)=>{
       //whatever
       fn(q)
   }
   fn(x)
})(0)

JavaScript provides a great solution for recursive functions: named function expressions . JavaScript为递归函数提供了一个很好的解决方案: 命名函数表达式 Hence I would recommend to use that instead of an arrow function: 因此我建议使用它而不是箭头功能:

(function fn(parameter) {
  // if, else ...
  fn(x);
})(0);

If you want to call recursive an lambda expression or anonymous function you need Y combinator . 如果要调用递归的lambda expressionanonymous function ,则需要Y组合子 For more details you can read http://mvanier.livejournal.com/2897.html 有关详细信息,请参阅http://mvanier.livejournal.com/2897.html

For factorial it is like 对于阶乘而言就像

 var Y = (proc) => { return ((x) => { return proc((y) => { return (x(x))(y);}); })((x) => { return proc((y) => { return (x(x))(y);}); }); }; var factorial = (fact) => { return (n) => { return (n === 0) ? 1 : n * fact(n-1); }; }; console.log( Y(factorial)(5) ); 

For you code it will be like 对于你的代码,它就像

const fn = (func)=> {

    return (parameter) => {
       // if else
       func(X);
    }
};

Y(fn)(0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM