Recursion और Tail Calls
एक recursive function खुद को call करता है, और एक tail call इसे stack बढ़ाए बिना ऐसा करने देता है।
In this page:
Recursion और Tail Calls
एक recursive function को local function से declare होना चाहिए ताकि इसका नाम इसकी अपनी body के अंदर visible हो। हर call stack space इस्तेमाल करता है, इसलिए बहुत deep recursion overflow कर जाता है। return f(x) फॉर्म की एक call Lua में एक proper tail call है और extra stack consume नहीं करती, इसलिए loops को tail recursion की तरह लिखा जा सकता है।
Note:
local f = function ... end के साथ नाम f body के अंदर अभी visible नहीं है, इसलिए local function इस्तेमाल करें या पहले declare करें।
उदाहरण: Recursion and tail calls
local function fact(n)
if n <= 1 then return 1 end
return n * fact(n - 1)
end
print(fact(5), fact(20))
local function sumTo(n, acc)
acc = acc or 0
if n == 0 then return acc end
return sumTo(n - 1, acc + n)
end
print(sumTo(100000))
-- Output:
-- 120 2432902008176640000
-- 5000050000
Login to try C/C++/Java/PHP code in the editor
आम गलतियां
- local f = function लिखना और इसके अंदर f call करना
- base case भूल जाना
- recursive call के बाद काम add करना और tail call खो देना
चैप्टर सारांश
- Recursion के लिए local function इस्तेमाल करें
- एक base case recursion रोकता है
- return f(x) एक tail call है
- Tail calls stack नहीं बढ़ाती
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: