Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
190
rated 0 times [  192] [ 2]  / answers: 1 / hits: 29805  / 10 Years ago, sun, august 10, 2014, 12:00:00

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 if just an anonymous function was being used.



Arrow functions cannot be named, so the named functional expression trick can not be used.



So... How does one write a recursive arrow function? That is an arrow function that recursively calls itself based on certain conditions and so on of-course?


More From » recursion

 Answers
2

Writing a recursive function without naming it is a problem that is as old as computer science itself (even older, actually, since λ-calculus predates computer science), since in λ-calculus all functions are anonymous, and yet you still need recursion.



The solution is to use a fixpoint combinator, usually the Y combinator. This looks something like this:



(y => 
y(
givenFact =>
n =>
n < 2 ? 1 : n * givenFact(n-1)
)(5)
)(le =>
(f =>
f(f)
)(f =>
le(x => (f(f))(x))
)
);


This will compute the factorial of 5 recursively.



Note: the code is heavily based on this: The Y Combinator explained with JavaScript. All credit should go to the original author. I mostly just harmonized (is that what you call refactoring old code with new features from ES/Harmony?) it.


[#69837] Friday, August 8, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
myrap

Total Points: 407
Total Questions: 105
Total Answers: 109

Location: Cambodia
Member since Thu, Oct 7, 2021
3 Years ago
myrap questions
Tue, Feb 8, 22, 00:00, 2 Years ago
Wed, Jan 15, 20, 00:00, 4 Years ago
Thu, Oct 24, 19, 00:00, 5 Years ago
Thu, Oct 3, 19, 00:00, 5 Years ago
Mon, Aug 12, 19, 00:00, 5 Years ago
;