tailrec Açıklaması
Garantili eniyileme
tailrec Açıklaması, CoddyKit'te ücretsiz bir Scala for Backend Engineering & Functional Programming dersidir. Bu, 4 dersinin 2. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, Scala for Backend Engineering & Functional Programming öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. Scala for Backend Engineering & Functional Programming kursu toplamda 4 dersten oluşur.
Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.
What is Tail Recursion?
A recursive call is in tail position when it is the very last action of the function. A tail-recursive function can be optimized into a loop, reusing a single stack frame, so it never overflows.
Tail Position
In n * factorial(n-1), the recursive call is not last: the multiplication happens after it returns. In gcd(b, a % b), the call is last. Only the latter is tail-recursive.
The @tailrec Annotation
Import scala.annotation.tailrec and annotate a method. The compiler then verifies the call is truly in tail position and applies the optimization. If it is not, compilation fails.
import scala.annotation.tailrec
object Main {
@tailrec
def countdown(n: Int): Unit = {
if (n >= 0) {
println(n)
countdown(n - 1)
}
}
def main(args: Array[String]): Unit = countdown(3)
}Guaranteed Optimization
The key benefit of @tailrec is the compile-time guarantee. You are told immediately if your function is not stack-safe, rather than discovering it via a runtime crash on large input.
A Tail-Recursive gcd
Euclid's algorithm is already tail-recursive: the recursive call is the entire body's result. Annotating it confirms this.
import scala.annotation.tailrec
object Main {
@tailrec
def gcd(a: Int, b: Int): Int =
if (b == 0) a else gcd(b, a % b)
def main(args: Array[String]): Unit = {
println(gcd(1071, 462))
}
}What Breaks Tail Position
Common patterns that move the call out of tail position:
- Doing arithmetic on the result:
n + f(...). - Wrapping in a constructor:
x :: f(...). - Using the result in a
tryblock.
Non-Tail Example
This sum is not tail-recursive because the addition wraps the call. Annotating it with @tailrec would cause a compile error. (Shown without the annotation so it runs.)
object Main {
def sum(n: Int): Int =
if (n == 0) 0
else n + sum(n - 1)
def main(args: Array[String]): Unit = {
println(sum(100))
}
}Why It Cannot Be Optimized
Because n + sum(n - 1) must remember n to finish the addition after the call returns, each level needs its own stack frame. The compiler cannot collapse this into a loop, so it is not tail-recursive.
A Large Tail-Recursive Loop
A tail-recursive sum using an accumulator runs for huge inputs without overflowing, because it reuses one frame.
import scala.annotation.tailrec
object Main {
@tailrec
def sumTo(n: Int, acc: Long = 0): Long =
if (n == 0) acc else sumTo(n - 1, acc + n)
def main(args: Array[String]): Unit = {
println(sumTo(1000000))
}
}tailrec Requires final or Local
For @tailrec to apply, the method must not be overridable: it must be private, final, or a local/nested method. An open method could be overridden, breaking the optimization, so the compiler rejects it.
Mutual Recursion Caveat
@tailrec only optimizes a function calling itself. Two functions calling each other (mutual recursion) cannot be tail-optimized by the JVM directly; for that you need trampolining, covered later.
Quick Check
Test your understanding of @tailrec.
Recap
You learned the @tailrec annotation:
- A call in tail position can be optimized into a loop.
@tailrecgives a compile-time guarantee of stack safety.- The method must be
final,private, or local. - It only covers self-recursion, not mutual recursion.
Sıkça Sorulan Sorular
“tailrec Açıklaması” dersi ücretsiz mi?
Evet — “tailrec Açıklaması” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve Scala for Backend Engineering & Functional Programming kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. Scala for Backend Engineering & Functional Programming kursu toplamda 4 dersten oluşur.
“tailrec Açıklaması” dersinde ne öğreneceğim?
Garantili eniyileme Scala for Backend Engineering & Functional Programming ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.
Scala for Backend Engineering & Functional Programming öğrenmeye başlamak için deneyim gerekli mi?
Önceden deneyim gerekmez. CoddyKit'te Scala for Backend Engineering & Functional Programming, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 2. dersidir.
“tailrec Açıklaması” dersi ne kadar sürer?
Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.
Bu Scala for Backend Engineering & Functional Programming dersinde kod yazıp çalıştırabilir miyim?
Evet. Her Scala for Backend Engineering & Functional Programming dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.
Bu kursun tüm dersleri
- Özyineleme Temelleri
- tailrec Açıklaması
- Biriktirici Örüntüsü
- Sıçrama Mekanizması