Loop (s) ≡ Recursive Function(s) ?
Table of Contents
Attention
Rewrite & translation in progress.
-- Abduaziz
Call Frame, Call Stack
Each time we call a function the context/information about that "call" will be stored. Simply, it (mainly) holds information such as return address, variables and arguments - the collection of those are called call frame. On each function call operation, new call frame is being formed & stored in stack, call stack precisely. In high-level(compared to assembly) programming languages, it is done implicitly, without our intervention.
Explanation(about return address): Let's assume that
helloandworldfunctions are called in sequence insidemain:int main(void) { hello(); world(); }After
hellofinishes its job, it must return back tomainsincemainhas to continue its own "path" and callworld. But, howhellosupposed to know where to come back (or return) ? Yes, it should remember "where it came from" and that is called "return address" and it is stored before switching into the function that is just being called. When it journey there is finished - it will use that stored return address in order to get back "where it came from".
You can inspect visual example from gdb(debugger) below, I'm walking step by step through code, and after each function call I'm able to see contents of call stack (call frame, local variables):

We can verify couple of things:
- Placing of call frames - stack property, LIFO
- Stored arguments and local variables
- Call frame of function which just finished is being removed
Let's have a look on different example:
int g(int x) {
return x+1;
}
int f(int x) {
// <... stuff ...>
return g(x);
}
When f is called, it will finish its "stuff" and calls g at the end (=f is creating call frame for g). Now, control is in g and the final result entirely depends on it. In Assembly (x86 arch, which we'll use through this article) call1 instruction is used to call function (duh).
Checkout our "C -> Assembly" translation (without optimizations):
Since we don't have traditional notion of "functions" in assembly, both f and g from our C source will be represented as labels there (e.g. see f: ... in assembly source). Its more like organizing entire source code into separated logical regions.
We said that, g will return into f after completing its missing. At the moment, we already have call frames for both of these - "returning back" means we switch from g's call frame into f's.
Is it necessary to "return back" from "g" to "f"?
Is there anything left on "f" that forces us to come back?
I would say "YES", if we had some sort of computation left on f after calling g but here NO.
Return back ?
After being done with f, if we directly execute the code of g without any formalities(e.g. call, return address stuff) result will be the same. This action is similar to glueing f's code with g into one label.
YES, we can't literally merge them, since code from g might be referenced/used later - in general it will be disaster. However, can we do some similar trick/workaround like this ?
For instance ... what if we reach to the end of f, we'll just directly jump into g's beginning ? Meaning, when CPU was executing last fragment of f, we'll just modify its instruction pointer towards g and then it will continue from g - like they've been merged.
Who has this power ? Not me, but jmp instruction has ! It does not think, just performs unconditional jump and it'll be used for building while/for loops (we'll get into this later).
FYI:
jmpinstruction is closestgoto(fromC) equivalent.
So, in cases when we don't have any reason to come/return back, we can/should just jump into target label.
In general(and for this case) - yes, g is being called in f's tail position, we can drop overhead from call's side and just directly jump into g(via jmp instruction) continiune from g and still get same behaviour. Does it feel like different convention of calling the functions ? Well, yes.
In Computer Science, we have a name for that convention - tail call.
"Formally", its impact from implementation perspective was studied & deeply discussed by Guy L. Steele (literally, call -> jmp thing, which we need). However, the idea of tail call has been shaped by he & Gerald Jay Sussman from their work on Scheme programming language.
Quote: "Procedure calls are, from a theoretical point of view, glorified GOTO statements; this view leads to interesting compilation techniques which can save space and time."
-- Guy L. Steele 2
The reason why I call it "specific case" is that we can't do this magic trick all time:
int g(int x) {
return x+1;
}
int f(int x) {
int y = x+2; // new
return y + g(x); // modified
}
If we jump to g directly, our program will behave incorrectly. Jumping(in this context) means "forgetting the frame of f(so that we don't come back), but for final result we need the value of y(local variable inside f) which is located inside f's frame and we can't refer to y from g's call frame.
After g(x), we are forced to come back to f(we can't forget it) for the value of y to compute final result (y+g(x)). No tail call thing.
Tiny Conclusion: Unfortunately, we have reason to come back (into
f) on example above.
Hmm, we can avoid from this by restructuring our code - meaning from non-"tail call" compatible code to "tail call"-able code, we'll talk about this in upcoming sections.
To utilize this trick, our call must be located into calling function's tail position. Another point is that code does not have to be the syntactically last statement to be consider as in tail position (tail position != last statement)
Comment: Code is in tail position when we don't have any extra computation left after this code finishes. Function can have more than one tail positons.
Example:
int g(int x) { return x+1; } int h(int x) { return x+2; } int f(int x) { if (x == 21) { return h(x); } else { return g(x); } }Here, apart from
g(x),f(x)has another tail position asreturn h(x)(onx = 21).
This is optimization, and compilers (gcc, clang) tries to do this magic in -O2/3 level optimizations, but does not guarrantee. However, we can get it via [[clang::musttail]]/[[gnu::musttail]]3 compiler attributes - but they're extensions (not in C/C++ standard). They must be explicitly put before return statement.
On Optimization Option/Level(s):
- GCC Optimizatation Options - https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html
- CLANG Optimization Options - https://clang.llvm.org/docs/CommandGuide/clang.html
We get the guarrantte, which means if compiler can do this optimization it will otherwise we'll get an error during compile time.
You can compare f_stock va f_tail(call vs jmp):
jmp ?
We saw that tail calls are done by replacing calls with jmp. In general, jmp does one thing - it changes the flow of execution(program, instruction's)
Our program(assembly instructions) normall will be executed in sequential order(top -> bottom), we can alter this via jmp (and make it spaghetti too).
Loops are also built on top of jmp, to repatetly execute one block of instructions we but jump so that it does backward jump and keeps rolling (yes, here we use conditional jumps, like jle - "jump if less or equal").
Tail Calls - Application/Adoption
As you might've noticed, this is basically assembly-level trick which is handled by C compilers (gcc/clang). What about the programming languages other than C ?
Hmm, in general if the programming language's compiler itself is implemented by C and built by gcc/clang - it should transform this kind of calls into tail calls. For example, Python's official implementation - CPython.
Do we have tail calls in CPython, in new type of interpreter yes but not in the way we thought.
Reference: "NOTE: This is not to be confused with tail call optimization of Python functions, which is currently not implemented in CPython.
This new interpreter type is an internal implementation detail of the CPython interpreter. It doesn’t change the visible behavior of Python programs at all. It can improve their performance, but doesn’t change anything else."
-- From CPython 3.14 release page
If interpreter is compiled by enabling --with-tail-call-interp flag via clang - on pyperformance average geometric mean speedup was ~3-5%[*]. But it[CPython] does does not make the python functions(that we write) tail calling as mentioned.
[*] it was different(more) initially, because of LLVM regression 4 .
Why it is not adopted/implemented (and won't) ?! 5
If you've debugging some code, you might've noticed this chain of function calls on UI/TUI which enables you to navigate through callstack, and inspect what's in there(e.g. mostly local variables' state). Debugger can take that sort of information from call frame only.
Because of this optimization[tail call], some of the call frames will be chopped-off and if debugger shows it as it is you're going to have hard time on figuring out execution flow.
That's why in most programming languages we'll have separate debug and release builds (e.g. some people benchmark debug build and complain about perfomance 🥲).
In case of CPython, it needs those call frames (exactly as it is) to print you traceback(stack trace during exception) on your terminal which is convinient and informative. Because of this and some other reasons, Guido says its unpythonic.
So no TCO in CPython, but if you're interested in implementation(like me) we have Lua.
"Research"
- https://github.com/lua/lua/blob/40b.../lvm.c#L1737-L1762
- Code for tail call preparation - https://github.com/lua/lua/blob/40b.../ldo.c#L665-L706
What about Recursion ?
In recursion function(s) will call itself(self recursion) & each-other(mutual recursion), it is kind of "hotspot" and TOC should become handay. For instance, let's see fibonacci (the only thing that appears on recursion demo)
// https://en.wikipedia.org/wiki/Fibonacci_sequence
int fibo(int n) {
if (n <= 1) return n;
return fibo(n - 1) + fibo(n - 2);
}
The reader, who understood the prerequisite for TOC can immediately notice that we can't to tail calls for the implementation above. We have even double-recursion (cherry on top), we have to "comeback" twice.


In recursion, the complexity of the algorithm will be measured according to its effect on callstack - i.e. how much it grows. On
fibothe total number of calls areO(phi^n)(where phi is golden ration and equal to 1.618) and depth of call stack isO(n)(maximum). "Stock" space complexityO(n), and time complexityO(phi^n)(mostly its simplified as 2^n).
Most of the the, the final result will be computed after all in recursive calls finished which means no intermediate results/accumulators (i.e. like we have in loops). One call will expand into another or multiple calls - fibo(10) -> fibo(9 & fibo(8), and later it will be "collected" - fibo(9) + fibo(8). If we visualize this, we can see triangular shape and a lot of repetitive calculations:
fibo(4) =
fibo(3) + fibo(2) =
( fibo(2) + fibo(1) ) + ( fibo(1) + fibo(0) ) =
( ( fibo(1) + fibo(0) ) + 1 ) + ( 1 + 0 ) =
( ( 1 + 0 ) + 1 ) + ( 1 + 0 ) =
( 1 + 1 ) + 1 =
2 + 1 =
3
Because of double-recursion, we can't have tail calls ? Is there anything we can do ?
Yes.
Analysis: transform double-recursion
By definition, we already know the values for fibonacci sequence for indices 0 and 1 - fibo(0) = 0 and fibo(1) = 1. Next values are computed from two previous values, and in general we should be able to n th fibonacci in n th iteration/call(don't mention the formula). We only need to know two previous values, the information about the sequence(only two values) should be passed by function's argument. Let's came up with optimized function implementation.
Terminaton condition is the same, if value is either 0 or 1 we'll finish. We have n which will determine how many steps we have to do, and two new variables for the context - current and next. Initial state:
0 -> 1 -> 1 -> 2 -> 3 ...
^ ^
| |
| next(default) => 1
current(default) => 0
We want our function to make steps/calls like iterative implementation, and expect its signature to be int fibo(int n, int current, int next).
To make that happen, we should provide default values for both current and next. Standard C does not have a support for it, with macros it will get messy and ugly. For that, we later define wrapper function which will call actual implementation with desired defaults.
In this new function, to reflect our intentions:
- We say that if
nis 0, then returncurrent(default). Initially, it will have 0. Otherwise, it holds accumulated value = the value of n th fibonacci sequence. - If
nis 1, then return backnext(default). Initially, it will have 1. - For other general cases, we say that: decrement
nby one (like iterative approach), ourcurrenthave value ofnext, andnextiscurrent + next.
In Python, it could've been current, next = next, current + next, in our C implementation we have this:
int fibo_impl(int n, int current, int next) {
if (n == 0) return current;
if (n == 1) return next;
return fibo_impl(n - 1, next, current + next);
}
To make the calling that convinient, we wrap it:
int fibo(int n) {
return fibo_impl(n, 0, 1);
}
Let's see how it will calculate when n is 4:


Until n hits the 1, it will keep expanding but now its "linear" growth (no triangular shape here). When it hits 1, it will return next which was passed previously as current + next.
Regarding Big-O metrics, time complexity reduced from O(phi^n) to O(n), but space complexity is the same O(n). We currently avoided from redundant calculations(values are being computed once), and no double-recursion !
It is called accumulator style recursive function, we can see this pattern in functional programming world.
"Better Call"
fibo_impl is doing self-recursin, and it is in tail positon ... did you notice something ?
Yes, now it can perform tail calls which it wasn't able to do before until we re-transformed it.
In function, if all recursive calls (can) make tial calls - we can call this function tail recursive function.
Terminology is getting weird(at least for me).
Tail Call Optimization(TCO) - general concept, can be applied for any sort of tail call - no matter whether it is recursive or not.
If compiler is applying TCO for recursive functions, they became tail recursive function and this special case is called Tail Recursion Elimination(TRE).
Why "eliminaton", we'll come to that later.
Example:
You can write those kind of accumulator-style functions in any other language, the question is whether your compiler does TCO for you. For example, I can do this in python:def fibo(n): def go(n, current, next): # well, I know about shadowing if n == 0: return current if n == 1: return next return go(n - 1, next, current + next) return go(n, 0, 1)Our shiny tail recursive version will work fine, but CPython doesn't care about optimization that we gave for it. CPython does not perform tail calls for
return go(n - 1, next, current + next)... As we mentioned, CPython uses tail calls for interpreter's core not for user's Python code.
On "eliminate", when TCO is applied(we must put compiler extension statement before return) for our latest fibonacci implementation all calls return fibo_impl(n - 1, next, current + next) will do tail call, which means all call instructions will be eliminated and replacted with jmp instructions.
Which meams, for recursive calls we are not creating any call frame inside callstack, rather using existing one (again and again). Recursion was eliminated - TRE.
As a result, our callstack does not grow linear(O(n)), we're using the same callframe repeatetively and here we get constant space complexity - O(1) space complexity.


We restructured the original algorithm, and dropped double-recursion into single self-recursion(+ no redundant calls, without memoization) and we been able to but that call on tial position. Which gave us O(n) time and O(n) space/stack.
Then, we zoomed out, got free support from our compiler for TRE, and now our call are replaced with jmp which is reusing same call frame. O(n) time and O(1) space/stack complexity !

Great!
Main purpose for TCO is not only to "fix" and speedup algorithms, rather security. It prevents us to witness stack overflow crashes(when you make so many recursive calls that fill entire call stack). And another benefit it ... (see next)
"Zoom-out" again
Iterative(built using loops) solutions are far more efficient than standard recursive ones:
- they don't use
call(duh) - they don't have callstack effect(no increase) and uses single call frame.
Hmm, our tail recursive implementation(e.g. fibo) also doing TRE, and consuming single call frame, each call implicitly became jmp instructions - which loops do too ...
Literally, same behaviour as loops!
Finding: If TCO is applied into tail recursive function, our iterative(loop-based) and recursive implementations became equivalent!
You can compare assembly of fibo_iter and fibo_tail_callni (without a wrapper) 7:
It is not byte-by-byte identical, but structually same thing.
Yeah, we can't say they are similarly effective from practicality (remember debugging case?), its easire to debug iterative code.
In some functional programming languages, it is encouraged to write recursive code rather than imprative loops(while, for) - many reasons for it, but its legit. Because their compiler can has TCO, and it can transform those recursive functions down to effectie imperative loops so that they can write recursive code without worrying. We can say this is the most application of TCO in industry.
The Answer For Title: If TCO is guaranteed in our language, self-recursive functions and their loop alternative implementation are semantically equal structure. We should note this iterative equivalence in linear recursion.
And this is:
- Incorrect/not applicable for Python.
- Partially correct/applicable in case of C.
- Totally correct for Schema because it is literally guarranteed by specification of language itself 8, for Scheme this is not just "optimization" - it is central part of language.
Mutual Recursion

We discussed about tail calls and self-recursion, mutual recursion deserves some discussion too.
// We know, nobody writes like this
bool is_even(unsigned int n) {
if (n == 0) return true;
return is_odd(n - 1);
}
bool is_odd(unsigned int n) {
if (n == 0) return false;
return is_even(n - 1);
}
Each one has single call in tail position, compiler can help us. They're just going to jump in between, nothing special:
Tekinga O(1) stack.
Reference: Took this example from
V8s blog on WebAssembly, please have a look - https://v8.dev/blog/wasm-tail-call#emscripten
There is not that much to say about the loops(and equivalance) in this case, we can't state that it will reflect the semantics of its loop-based implementation(if any). But transforming this(recursion) into iterative approach can be discussed.
In self-recursion it can be done easily, the body of the function will eventually become body of the loop.
In mutual recursion, we have two function bodies, and if we take same route we should have two loop bodies. How we manage that ? Well, inside our loop, we execute the body of one of those functions(is_even/is_odd) according to state. We'll introduce variable(e.g. enum or boolean, here we have two functions - boolean can represent that) which will enable us to transform this mutual recursion into imperative loop. But, we can't manage to original semantics (structure), because we're forced to introduce new variable for state.
If you wonder why we would need mutual recursion (who writes this is_even/odd), you might try to implement Finite State Machines, parsers(m: Recursive Descent) etc.
"StackOverflow" Problem
You wrote a recursive algorith, it is workign as expected and now you want to give try for bigger inputs which will lead into deeper/more recursive calls. As a result, you'll endup filling your callstack with such many calls, and your program crashes - stack overflow.
For instance, CPython has a static limit for recursion depth, by default its 1000:
Python 3.14.2 (main, Jan 27 2026, 23:59:57) [Clang 21.1.4 ] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys; print(sys.getrecursionlimit())
1000
If you want to cross that:
def factorial(n:int) -> int:
if n == 0: return 1
return n*factorial(n-1)
>>> factorial(5)
120
>>> factorial(1001)
Traceback (most recent call last):
...
RecursionError: maximum recursion depth exceeded
Even accumulator-style tail recursion wouldn't help:
def factorial(n:int) -> int:
def go(n:int, acc:int) -> int:
if n == 0: return acc
return go(n-1, acc*n)
return go(n, 1)
>>> factorial(5)
120
>>> factorial(1001)
Traceback (most recent call last):
...
RecursionError: maximum recursion depth exceeded
Increasing the recursion depth is one of good footguns, even if you're managed to increase it in CPython interpreter, we hae C code being run - you can't modify this easily(from interpreter). Even if you bypass everything, you still might hit that C stack limit, and your python program will "segfault" which CPython tries to avoid at all cost.
To harden this case, CPython core development implementing mechanisms for that, one of them which:
Reference: "Protection against pure Python stack recursion has existed since very early, but in 3.12 we added protection against stack overflow in C code. This was initially implemented using a counter and later improved in 3.14 to use the actual stack depth.
-- Internal Docs - Stack Protection
Conclusion: if we have TCO
The answer for the title is yes, if we think in terms of language agnostic setup - in case of TCO support loops and recursive functions are pretty much same.
TCO enables you to have same efficiency in recursive code as you have in impreative loops, and also it will serve as a security measurement by "stopping" the growth of your program's callstack.
What if we DON'T have TCO ?!
said you, right ? ...

Lazyyyy ...
So, do we just keep looking at stackoverflows in that case ? "You're absolutely wrong", if that was the case what's the point of continuing the article.
We have an implementation which supports tail recursion, e.g. that might've been implemented in accumulator style. No matter that, call stack will grow linear and we exactly know when we're going to hit the recursion limit.
Our goal is to make sure that we won't make it grow.
We're using Python for implementation, you might find support code from "Appendix" part.
The example is stupid, but tail recursive:
def funksiya(n: int) -> CallableOrResult[str]:
if n == 0:
return "tugadi"
return funksiya(n - 1)
It will go till 0 and then returns "tugadi" which fills the call stack on its way.
>>> funksiya(3)
'tugadi'
>>> funksiya(1_000)
Traceback (most recent call last):
...
RecursionError: maximum recursion depth exceeded
Let's see how funksiya(3) is being executed:
funksiya(3) -> started
funksiya(2)
funksiya(1)
funksiya(0) -> "tugadi"
When it hits funksiya(0), it will stop from expanding and propagates "tugadi" on top:
funksiya(0) -> return "tugadi"
funksiya(1) # "tugadi"ni qaytaradi
funksiya(2)
funksiya(3) -> "tugadi" tepadan shu yergacha keladi, va qaytariladi
return "tugadi" bajarilguncha hammasi call stackda turib joy oladi, funksiya(0) call stackning eng tepasiga keladi, return bajariladi, keyin hamma framelar bitta-bitta stackdan pop qilinadi. Ungacha esa Hanoi minorasini quramiz, kattaroq qiymat bersak minoramiz juda baland bo'ladi va rekursiya chegarasini urib qo'yamiz - stack overflow.
funksiya(0)gacha borish uchun, butun boshli call stackni shishirib borish shartmi ? Hammasini soddalashtirsak, funksiya(3) ketma-ket yurib funksiya(0)ni qaytarib qo'ysa bo'ldi ekanligini guvohi bo'lamiz (lekin hali isbotlamadik). funksiyani ketma-ketlikni saqlagan holda birin ketin chaqirib/bajarib ham natijaga erishishimiz mumkin.
Ketma-ketlik bor, lekin rekursiv chaqiruvlar sababli ular ichma-ich kirib ketyapdi - biz xohlagandek chiziqli emas (tepadagi vizualizatsiyaga qarang).
funksiya(3)ni chaqirishimiz bilanoq, zanjir reaksiyasi yuzaga kelyapdi, nazoratni ololmay qolyapmiz va funksiya chaqiruvlari kengayib ketyapdi. Ular biz xohlagan tartibda chaqirilyapdi, ammo xohlagan vaqtimizda emas + har bir funksiya chaqiruvi, yangi call frame yaratmasligi zarur. CPythonda mavjud freymni qayta ishlatishga majburlay olmaymiz, ammo ularning sonini maksimum 1 taga tutib turishimiz mumkn.
Bu uchun bitta fokus bor - "lazy evaluation". Keng tarmoqli tushuncha, bizning kontekstida qo'llanilganida - funksiya chaqirilish/bajarilishini kechiktirishga nisbatan foydalaniladi va bizga optimizatsiya eshigini ochadi. Bu uslub "control flow" tuzilmalarini ifodalashda keng qo'llaniladi.
Xullas, "bola yig'lamasa, onasi sut bermaydi" degan vaziyat kabi, "nimanidur" faqat aynan kerak vaqti bajaramiz.
CPythondagi
rangeham shunday "lazy"(dangasa) tuzilma.values_list = [ ... ] # millionta sonlar # vs values_range = range(1_000_000)
for value in values_list: ...bo'lsa -values_listholatida barcha millionta qiymatlar xotirada saqlanadi, lekin bir vaqtda hammasi kerak emas.for value in values_range: ...bo'lsa -values_rangeholatida esa yo'q, har bir iteratsiyada bitta-bitta qiymat olinadi kerak vaqtida. "Lazy" & xotira tejaladi.
Biz funksiya chaqiruvlarini ham "lazy" qilishimiz mumkin va keyin funksiya chaqiruvi kechikadi("defer"). CPython holatida buni bevosita ta'kidlaymiz, lambda orqali:
def hey() -> None:
print("hello world, hey")
hey_lazy = lambda: hey()
Juda ham zo'r misol bo'lmagan bo'lsa uzur.
Endi funksiya holatiga qaytamiz, rekursiv chaqiruvimizni kechiktirib, "lazy" holda chaqiramiz:
Eslatma: Koddagi tipga oid annotatsiyalarni "Appendix" qismidan topasiz (m:
FunctionOrResult)
def funksiya(n: int) -> FunctionOrResult[str]:
if n == 0:
return "tugadi"
return lambda: funksiya(n - 1) # o'zgardi
Endi funksiya(3)ni chaqirganimizda nima sodir bo'ladi.
funksiya(3) => return lambda: funksiya(2)
Tamom. Biz rekursiv chaqiruvni amalga oshirmayapmiz, uning o'rniga yangi lambda obyektini yaratib keyin qaytaryapmiz. Call stackga yangi element qo'shilmaydi, chunki qiymat(yangi funksiya) zudlik bilan qaytariladi va chaqirilgan funksiya yakuniga yetadi. Hamda unga tegishli call frame ham call stackdan chopiladi ! Maksimum 1 taga ushlab turyapmiz.
Lekin hozir tepada biz xohlagan yakuniy qiymat("tugadi") emas balki lambda obyekt/funksiyasi qaytdiku ? Ushbu lambda obyektini chaqirsak bizga yana yakuniy qiymat o'rniga yangi obyekt qaytariladi (funksiya(1)). Eng oxirigacha borish uchun shu tarzda chaqirishda davom etsak "tugadi" qaytadi lambda obyektining o'rniga:
funksiya(3) => return lambda: funksiya(2) # lambda obyekti
|
funksiya(2) => return lambda: funksiya(1) # lambda obyekti
|
funksiya(1) => return lambda: funksiya(0) # lambda obyekti
|
funksiya(0) => return "tugadi" # yakuniy qiymat !
Har safar lambda qaytgani sababli, yakuniy javobni olish uchun ularni har safar bir necha qayta marta chaqirishga majburmiz.
result = funksiya(3) # lambda obyekti
result = result() # lambda obyekti
result = result() # lambda obyekti
result = result() # "tugadi"
# yoki barchasi bittada
funksiya(3)()()() # 0
Qiziq tomoni, biz "qo'lda" 4 marta ketma-ket chaqiruvni amalga oshirgan bo'lsakda, call stackdan faqat 1 ta call frameni ishlatdik (chunki ketma-ket != ichma-ich). funksiya(3) chaqirildi, qiymat qaytdi (frame endi kerak emas). Keyin qaytgan qiymat chaqirildi, yangi qiymat qaytdi keyin frame ham chopildi va javobni olguncha davom etamiz.
O'ng tomondagi "Call Stack" panelidagi holatni solishtirib ko'ring:
-
funksiya(10)- oddiy rekursiv
Default -
funksiya(10)- yuqoridagi lambda qaytaradigan uslub orqali
Thunk-based
E'tibor: Shu joyida bir detailni eslatib o'tay, biz hozir qilgan o'zgarishlarimiz sababli funksiya chaqiruvini vaqtinchalik kechiktirib "pauza" qilishga erishdik ! Birinchi talqinida unday emas edi, hozir
funksiya(3)ni chaqirgandan keyin qaytganfunksiya(2)ni chaqirmadik. Balki kichik pauza(suspend) qildik, keyin xohladik va chaqirdik. Bu sizga Python dasturlash tilidagi qaysidur konseptni eslatmayapdimi ? O'ylab turing.
Funksiyalarni va ular qaytargan qiymatlarni tenglik ko'rinishida yozib olib tahlil qilamiz:
funksiya(3) = lambda: funksiya(2)
funksiya(2) = lambda: funksiya(1) # Ya'ni funksiya(2)ning o'rnini lambda: funksiya(1) bosa oladi. To'liq ekvivalent
funksiya(1) = lambda: funksiya(0) # Same
funksiya(0) = "tugadi"
Eslatma: Kamida boshlang'ich algebra/matematika o'qiganlar, o'rin almashtirish(substitution) bilan tanish. Masalan:
z = 2y x = y + z bo'lsa x = y + z # ifodada, z`ni o'rnini 2y bilan almashtirishimiz mumkin - tepadagi tenglikdan kelib chiqib. x = y + 2y = 3y x = 3y # z`ni 2y bilan substitute qildik
Endi tepadan boshlab, mavjud lambda ifodalarni pastdagilari bilan substitute qilib ifodalaymiz.
funksiya(2) = lambda: funksiya(1) tengligi sababli:
funksiya(3) = lambda: ( lambda: funksiya(1) )
^^^^^^^^^^^^^^^^^^^
Keyin esa funksiya(1) = lambda: funksiya(0) sababli:
funksiya(3) = lambda: ( lambda: ( lambda: funksiya(0) ) )
^^^^^^^^^^^^^^^^^^^
Vanihoyat, funksiya(0) = "tugadi" tufayli:
funksiya(3) = lambda: ( lambda: ( lambda: ( "tugadi" ) ) )
^^^^^^^^
funksiya(3)ni qanday ifodalaganimizni ko'rdingizmi ! Biz "lazy" funksiyamizni bilvosida qanday qayta qurilishini tahlil qildik. Endi u o'z-o'zini qayta chaqirishi shart emas, "tugadi"gacha yetib borish uchun avvalgi chaqirilgan funksiyalarning call frame'ini eslab qolishga ham majbur emas.
Kichik Xulosa: Funksiya tuzilishidan ko'zga chuqurlashib borayotgandek ko'rinadi. Ammo, har bir funksiya chaqiruvi bizga yangi keyinchalik "chaqirilish xossasiga ega"(callable) lambda obyektini qaytaryapdi. Ushbu obyektni qaytargan lambda funksiyaning call framei kerak bo'lmagani sababli u call stackdan chopilib ketadi. Ushbu qaytarilgan obyektni chaqirsak yana bir xil ssenariy toki yakuniga bormaguncha. Natijada har bir chaqiruv, yana bir chaqiruvni amalga oshirmaydi va bizda call stack umuman o'smaydi.
Muammo shundaki, bundan to'liq bahramand bo'lish uchun def funksiya(n)ni nechi marta yoki qachongacha chaqirishni aniq bilishimiz darkor, va bunda hech qanday rekursiv chaqiruvlarsiz yakuniy natijagacha bora olamiz keyin.
Qo'lda TCO
nning qiymati 1000 bo'lganida ming marta () qilishni xohlamasligimizni bildik. Lekin, buni aynan necha marta qilishimizni barcha holatlar uchun aytib beradigan deterministik yo'li ham mavjud emas (=men bilmayman).
Lekin python "free-style" bo'lgani sababli bu ish uchun yordamchi funksiya yaratishimiz mumkin. U faqat bitta ishni qiladi - berilgan funksiya chaqirilgandan keyin natijasi lambda obyekt bo'lsa - uni chaqiradi, aksincha bo'lsa uni yakuniy natija deb qabul qilib natijani qaytaradi.
Yordamchi funksiyamiz "high-order" ya'ni boshqa funksiyani argument sifatida qabul qiladigan funksiya:
def helper(func):
"""
agar func argumentimiz chaqirish("call") xossasiga
ega qiymat("call" -> "callable") bo'lsa,
uni chaqirishda davom etib oxirgi qiymatini
saqlashda davom etamiz.
Natija "callable" bo'lmasa, demak u bizning oxirgi qiymatimiz.
Va uni qaytaramiz.
"""
pass
Implementatsiya:
def helper[T](func: FunctionOrResult[T]) -> T:
function_or_result: FunctionOrResult[T] = func
while callable(function_or_result):
function_or_result = cast(Thunk[T], function_or_result)
function_or_result = function_or_result()
return function_or_result
Ishimizni avtomatlashtirdik.
>>> helper(funksiya(1_000_000)) # rekursiya chegarasidan x1000 katta
'tugadi'
Tail positionda turgan funksiyalar chaqiruvini keyinga qoldirib(defer), xohlangan natijaga erishdik. Call stack to'lish muammosidan qutuldik ! va jarayonni to'liq avtomatlashtirdik. functools.partialga o'xshagan nimadur yozib helperga yedirmasangiz, barchasi joyida.
Accumulator-style tail rekursiv fibonachi ham bor edi:
def fibo(n: int) -> CallableOrResult[int]:
def go(n: int, current: int, next: int) -> CallableOrResult[int]:
if n == 0:
return current
if n == 1:
return next
return go(n - 1, next, current + next)
return go(n, 0, 1)
>>> fibo(1000)
Traceback (most recent call last):
...
RecursionError: maximum recursion depth exceeded
>>>
funksiyadagi kabi bir xil uslubni qo'llaymiz:
def fibo(n: int) -> FunctionOrResult[int]:
def go(n: int, current: int, next: int) -> FunctionOrResult[int]:
if n == 0:
return current
if n == 1:
return next
return lambda: go(n - 1, next, current + next) # o'zgardi
return go(n, 0, 1)
>>> helper(fibo(10_000))
33644764876431783266621612005107543310302148460...
Zo'r. Rasmiyatchilikga kelsak:
funksiyavafibomisolida quyidagi kabilambda: <funksiya>qaytarilayotgan funksiyalar/ifodalar - thunk deb nomlanadi va funksiya chaqiruvini kechiktirish uchun foydalaniladi. E'tibor bering, thunklar argument olmaydi. Menimcha koddagiThunk[T]ni ko'rib ikkilangan bo'lsangiz.- Biz ishlatgan
helperfunksiyaga alohida nom bor - trampoline(tramplin). - Va o'zi ushbu uslub/texnikaning nomi ham "Trampolining" sanaladi.

Nega tramplin ? Rekursiyada funksiyalar chaqiruvi ichma-ich bo'lib kirib ketadi. Tramplinlar holatida esa har bir chaqiruvdan keyin, funksiya yakunlanib - nazorat yana tsikl/tramplinga qaytadi (ya'ni helper funksiyamizga). Hayotdagi tramplinlardagi kabi, sakraymiz yana tramplinga qaytib tushamiz va yana sakraysiz ("bouncing back"). Endi helper funksiyamizni sekingina trampoline deb nomlab qo'yamiz.
Eslatma: Bu atama funksional dasturlashdan avval, boshqa sohalar shu jumladan "systems programming"da ham qo'llanilib kelingan/kelinyapdi. Tramplin haqida google qilganingizda "indirect jumplar, JIT va hk."lardagi tramplinga oid materiallar bilan adashib ketmang.
Tepada aytganimdek bu TCO kabi bizga iterativ uslubga yaqin samaradorligini bermaydi - balki sekinlashtiradi. Chunki biz lambdalar orqali closure'lar yaratyapmiz, bunda heap(dinamik xotira)dan ko'p marotaba joy ajratishimizga to'g'ri keladi.
Asosiy maqsadimiz stackoverflow muammosidan qutilish edi va biz buni uddaladik. Trade-offlar ham bor guvohi bo'lganingizdek.
"Trampoline - poor man’s Tail Call Optimization (TCO)"
Esladingizmi ?
Tepada "O'ylab turing" degan edim.


Shuncha qilgan amallarimiz bilan biz Pythondagi generatorlarni bir qismini qayta ixtiro qildik ya'ni bizniki faqat tashqaridan qiymat ololmaydi.
Ma'lumot(Generatorlar):
"Lazy evaluated" tuzilma sanaladi, ko'pincha 2 xil usulda yaratiladi.# Generator expression value = (x**2 for i in range(100)) # Generator funksiya def gen_x(): for i in range(100): yield i value = gen_x()Funksiya ichida
yieldkalit so'zi bo'lsa, funksiyamiz generator funksiyaga aylanadi. Generator funksiyalar 1-marta chaqirilganda generator obyektini qaytaradi.Ular bizga murakkab iteratorlar ketma-ketligini yozishda qo'l keladi.
Ikkisi ham "lazy evaluated" tuzilma, bajarilishi davomida pauza qilish ham mumkin va natija o'rniga biri "thunk", ikkinchisi esa generator obyektini qaytaradi. Yuqoridagi yechimni generatorlar asosida qurish mumkin:
def funksiya(n: int) -> GeneratorOrResult[int]:
if n == 0:
return "tugadi"
yield funksiya(n - 1) # o'zgardi
yield tufayli funksiyamiz function generatorga aylandi. Uni avvalgidek chaqira olmaymiz, endi qaysiki funksiya(3) ifodasi generator obyektini qaytaradi (bizniki lambda obyekti qaytarganidek). Uni faqat next(...) built-in funksiyasi orqali keyingi bosqichlariga o'tkazib boramiz ("funksiya chaqiruvi" -> next(...)).
Tramplindagi tsikli shartida natijani agar funksiya bo'lsa chaqiramiz degan maqsadda callable tipiga qarshi tekshirayotgan edik. Endi shu ishni generator uchun bajaramiz, yangi tramplin:
def trampoline[T](func: GeneratorOrResult[T]) -> T:
generator_or_result: GeneratorOrResult[T] = func
while isinstance(generator_or_result, types.GeneratorType):
try:
generator_or_result = next(generator_or_result)
except StopIteration as exc: # qo'shimcha detail
generator_or_result = exc.value
return cast(T, generator_or_result)
Generatorlar qiymatlarini ketma-ket yield orqali qaytaradilar(iterativ uslubga o'xshash), ammo bizning funksiyalarimiz yakuniy natijani return bilan qaytaryapdi. Ketma-ketlik yakunlanganligini bildirish uchun, CPythonda generator yakunida StopIteration exception'i chaqiriladi va qaytgan qiymatni undan olishimiz mumkin.
Izoh: "In a generator function, the return statement indicates that the generator is done and will cause StopIteration to be raised. The returned value (if any) is used as an argument to construct StopIteration and becomes the StopIteration.value attribute."
-- https://docs.python.org/3/reference/simple_stmts.html#the-return-statement
Endi navbat fibonachiga:
def fibo(n: int) -> GeneratorOrResult[int]:
def go(n: int, current: int, next: int) -> GeneratorOrResult[int]:
if n == 0:
return current
if n == 1:
return next
yield go(n - 1, next, current + next) # o'zgardi
yield go(n, 0, 1) # o'zgardi
Yuqoridagi kod chaqirilganda, generator obyektini qaytaradi. Qaysiki avvaliga lambda funksiya edi. Obyekt yaratib, qiymatni qaytarganimizda - call frame o'chib ketadi, endi kerak emas. yield holatida bu ishni bilvosida bajaryapmiz, yangi generator obyektlari zanjirini xosil qilib.
Ikkisining natijasi bir xil, 2-sida bosh og'riqlar biroz kam. return o'rniga yield ishlatinglar, muammo hal desam ham bo'lar edi - lekin "Nega va qachon yield ishlatishimiz mumkin/kerak ?!" degan savolga aniq javob berishimiz keyin qiyin bo'lardi.
Ikkala ("thunk" va generator) uslubni ham profiling qilib ko'rdim, vaqt va xotira jihatidan deyarli bir xil ko'rsatgichlar (memray sizning do'stingiz).
"Innan" keyinchi ?
Biz bajargan mashg'ulotlar koroutinlar uchun asos sanaladi. CPython holatida avvaliga asinxron dasturlash asoslari generatorlar ustiga qurilgan va xuddi tepadagi kabi ularni boshqaradigan katta tsikl ham mavjud bo'lgan. Biz uni tramplin emas, event loop deb atab kelmoqdamiz :).
Farqi, event loop tramplin kabi bitta emas, balki bir nechta thunk(event loop kontekstida koroutin)larni boshqaradi. Ya'ni ularni saqlaydi(m: listda), ular bo'yicha yurib chiqib, hammasini keyingi "step"ga o'tkazib chiqadi. yield orqali funksiya bajarilishini pauza qilamiz, va keyingi funksiyaga o'tamiz, uni ham pauza qilamiz, va hokazo - qaytib kelib davom etamiz toki barcha yakunlangan funksiya/generatorlar listdan chopilmaguncha.
Ushbu bir marta yurib chiqish qanchalik tez bo'lsa, bizga bir-nechta thunk/koroutinlar shuncha parallel bajarilayotgandek ko'rinadi ! Hmm, aniqroq aytganda concurrent (Concurrency is not Parallelism).
Ko'proq(Back History):
- PEP 342 - https://peps.python.org/pep-0342
- PEP 492 - https://peps.python.org/pep-0492
Menimcha, kattaroq rakursdan qaraganda: tail calllar, generatorlar, koroutinlar uchun umumiy fundamental mavzulardan biri "continuation"lar sanalsa kerak. Biz tepada o'rgangan narsalar bilan ishlash prinsipi birozgina farqga ega bo'lsada yetarlicha o'xshash. Diskleymer: "callback"lar bilan chalkashtirmang.
"Continuation-passing style (CPS)" haqida ko'proq izlanib ko'rishingiz mumkin. Asinxron dasturlashda, control flowni boshqarishda u bilan chiroyli ishlar qilish mumkin. TCOdan foydalanadigan asosiy katta mijozlardan sanaladi.
Xulosa: TCO mavjud bo'lmaganda
Kompilyatorlar "Tail Call Optimization"da bajarayotgan ishni biz tramplinlar orqali qo'lda qilib ko'rdik.
Demak, TCO qo'llab-quvvatlanmagan tilda, sizda chuqur rekursiv chaqiruvlarga ega funksiya mavjud bo'lsa tanlov qilishga majbursiz - chunki "potensial" stack overflow muammosi xavfi mavjud:
- 1 - tanlov: Iterativ usulda yozib ko'rasiz tsikllar yordamida.
- 2 - tanlov: TCO qo'llab quvvatlanMAsa dasturlash tilingizda - funksiyani accumulator-style'ga o'tkazib, tail rekursiv variantda yozib ko'rasiz. Hamda uni tramplinlar bilan ishlaydigan ko'rinishga keltirib, tramplinga berib foydalansangiz bo'ladi.
X- tanlov: < Universal javob bo'lmasligi mumkin, bu tanlov variantini sanab o'tilmagan boshqa mavjud texnikalar uchun qoldiraman >
X-tanlov: Python uchun - Stackless Python, Greenletlar bo'lishi mumkin, lekin ushbu ekotizim hozirda faol ravishda qo'llab-quvvatlanmaydi.
Vazifalar
- Faktorial funksiyasini o'zingiz bilgan tilda tail rekursiv talqinida yozib izohlarda qoldiring.
- O'zingiz ishlatadigan(Pythondan tashqari) tilda tramplin yasab ko'ring.
- O'zingizning "Event Loop"ingizni yasang, trampolineni o'zgartirib minimal yechim qilish ham mumkin.
- https://medium.com/@veedrac/one-weird-trick-to-reduce-cpython-s-function-call-overhead-by-25-3a4d665c503a
E'tibor uchun alohida tashakkur
"Revision History"
- 24.06.2026 - ba'zi imloviy va uslubiy xatolar to'g'rilandi - @loga4m.
Appendix
Kod mening Github Gist sahifamda.
-
https://www.felixcloutier.com/x86/call#description, undan keyin https://cs.brown.edu/courses/csci0300/2021/notes/l07.html ↩
-
Guy Lewis Steele. 1977. Debunking the “expensive procedure call” myth or, procedure call implementations considered harmful or, LAMBDA: The Ultimate GOTO. In Proceedings of the 1977 annual conference (ACM '77). Association for Computing Machinery, New York, NY, USA, 153–162. https://doi.org/10.1145/800179.810196. ↩
-
[[gcc::musttail]]- https://gcc.gnu.org/onlinedocs/gcc-15.1.0/gcc/Statement-Attributes.html#index-musttail-statement-attribute ↩ -
"CPython Tail Call" -- https://blog.nelhage.com/post/cpython-tail-call. ↩
-
Guido van Rossum. 2009. Blogger page. https://neopythonic.blogspot.com/2009/04/tail-recursion-elimination.html. Argumentlar o'rinli, lekin qizg'in muhokamalarga boy bo'lgan "dramma". ↩
-
Bu yerda
fibo_tail_call"wrapper" vazifasida kelyapdi, funksiya chaqiruvini chiroyliroq bo'ladi - har safar boshlang'ichcurrentvanextbevosita ko'rsatilishi shart emas. Bu kabi ichki funksiyalargoyokiloopdeb nomlash an'anasi bor (Haskell/OCaml mentioned). ↩ -
Optimizatsiya darajasini
-O1ga qo'ydim, undan yuqorisi "avtomatik vektorlash"(auto-vectorization)ni ham qo'llab bizni chalkashtiradi va biz keyin mavzudan chetga chiqishga majbur bo'lishimiz mumkin. Lekin bufibo_itervafibo_tail1 ga 1 assembly chiqaradi degani emas, tuzilish jihatdan ekvivalent, "byte by byte" emas. ↩ -
https://standards.scheme.org/corrected-r7rs/r7rs-Z-H-3.html ↩
Cryptographic Authenticity of Current Page
Manual steps, or see below for "all in one":
- Get my RSA public key from GitHub or Codeberg.
- Get current page's RSA signature
-
Get current page's HTML source - save or via
curl,wget -
Create
allowed_signersfile mapping my email into this public key - Finally, verify via
ssh-keygen - Drink some tea
(
export EMAIL="..." SLUG="loops-recursive-functions"
export URL="https://abduaziz.ziyodov.uz/$SLUG"
mkdir -p /tmp/verify && cd /tmp/verify && \
curl $URL.html.sig > $SLUG.html.sig && \
curl https://codeberg.org/Abduaziz.keys > key.pub && \
curl $URL > $SLUG.html && \
printf "%s %s\n" $EMAIL "$(cat key.pub)" > allowed_signers
ssh-keygen -Y verify -f ./allowed_signers -I $EMAIL -n file \
-s $SLUG.html.sig < $SLUG.html
)