How do I write an arrow function in ES6 recursively?

后端 未结 12 819
南旧
南旧 2020-12-08 06:36

Arrow functions in ES6 do not have an arguments property and therefore arguments.callee will not work and would anyway not work in strict mode even

相关标签:
12条回答
  • 2020-12-08 07:00

    Since arguments.callee is a bad option due to deprecation/doesnt work in strict mode, and doing something like var func = () => {} is also bad, this a hack like described in this answer is probably your only option:

    javascript: recursive anonymous function?

    0 讨论(0)
  • 2020-12-08 07:03

    It looks like you can assign arrow functions to a variable and use it to call the function recursively.

    var complex = (a, b) => {
        if (a > b) {
            return a;
        } else {
            complex(a, b);
        }
    };
    
    0 讨论(0)
  • 2020-12-08 07:08

    A general purpose combinator for recursive function definitions of any number of arguments (without using the variable inside itself) would be:

    const rec = (le => ((f => f(f))(f => (le((...x) => f(f)(...x))))));
    

    This could be used for example to define factorial:

    const factorial = rec( fact => (n => n < 2 ? 1 : n * fact(n - 1)) );
    //factorial(5): 120
    

    or string reverse:

    const reverse = rec(
      rev => (
        (w, start) => typeof(start) === "string" 
                    ? (!w ? start : rev(w.substring(1), w[0] + start)) 
                    : rev(w, '')
      )
    );
    //reverse("olleh"): "hello"
    

    or in-order tree traversal:

    const inorder = rec(go => ((node, visit) => !!(node && [go(node.left, visit), visit(node), go(node.right, visit)])));
    
    //inorder({left:{value:3},value:4,right:{value:5}}, function(n) {console.log(n.value)})
    // calls console.log(3)
    // calls console.log(4)
    // calls console.log(5)
    // returns true
    
    0 讨论(0)
  • 2020-12-08 07:09

    TL;DR:

    const rec = f => f((...xs) => rec(f)(...xs));
    

    There are many answers here with variations on a proper Y -- but that's a bit redundant... The thing is that the usual way Y is explained is "what if there is no recursion", so Y itself cannot refer to itself. But since the goal here is a practical combinator, there's no reason to do that. There's this answer that defines rec using itself, but it's complicated and kind of ugly since it adds an argument instead of currying.

    The simple recursively-defined Y is

    const rec = f => f(rec(f));
    

    but since JS isn't lazy, the above adds the necessary wrapping.

    0 讨论(0)
  • 2020-12-08 07:11

    Use a variable to which you assign the function, e.g.

    const fac = (n) => n>0 ? n*fac(n-1) : 1;
    

    If you really need it anonymous, use the Y combinator, like this:

    const Y = (f) => ((x)=>f((v)=>x(x)(v)))((x)=>f((v)=>x(x)(v)))
    … Y((fac)=>(n)=> n>0 ? n*fac(n-1) : 1) …
    

    (ugly, isn't it?)

    0 讨论(0)
  • 2020-12-08 07:12

    Claus Reinke has given an answer to your question in a discussion on the esdiscuss.org website.

    In ES6 you have to define what he calls a recursion combinator.

     let rec = (f)=> (..args)=> f( (..args)=>rec(f)(..args), ..args )
    

    If you want to call a recursive arrow function, you have to call the recursion combinator with the arrow function as parameter, the first parameter of the arrow function is a recursive function and the rest are the parameters. The name of the recursive function has no importance as it would not be used outside the recursive combinator. You can then call the anonymous arrow function. Here we compute the factorial of 6.

     rec( (f,n) => (n>1 ? n*f(n-1) : n) )(6)
    

    If you want to test it in Firefox you need to use the ES5 translation of the recursion combinator:

    function rec(f){ 
        return function(){
            return f.apply(this,[
                                   function(){
                                      return rec(f).apply(this,arguments);
                                    }
                                ].concat(Array.prototype.slice.call(arguments))
                          );
        }
    }
    
    0 讨论(0)
提交回复
热议问题