foldLeft ve foldRight
Koleksiyonları tek bir değere indirgeyin.
foldLeft ve foldRight, CoddyKit'te ücretsiz bir Scala for Backend Engineering & Functional Programming dersidir. Bu, 4 dersinin 3. 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.
Folding a Collection
Folding collapses a collection into a single value by repeatedly combining elements with an accumulator.
The accumulator pattern you learned is exactly what fold abstracts. Instead of writing the recursive helper yourself, you pass in a starting value and a combining function.
foldLeft Basics
foldLeft takes an initial accumulator and a function (acc, element) and walks the collection from left to right.
At each step it replaces the accumulator with the function's result.
val xs = List(1, 2, 3, 4)
val total = xs.foldLeft(0)((acc, x) => acc + x)
@main def run(): Unit =
println(total) // 10How foldLeft Associates
foldLeft brackets from the left. For List(1, 2, 3) with seed z it computes f(f(f(z, 1), 2), 3).
The accumulator is the left argument, so it accumulates as you move rightward through the list.
// List(1, 2, 3).foldLeft(0)(_ + _)
// = ((0 + 1) + 2) + 3
// = 6foldRight Basics
foldRight also combines elements but starts from the right.
Its function takes (element, acc), with the element on the left and the accumulator on the right.
val xs = List(1, 2, 3, 4)
val total = xs.foldRight(0)((x, acc) => x + acc)
@main def run(): Unit =
println(total) // 10How foldRight Associates
foldRight brackets from the right. For List(1, 2, 3) with seed z it computes f(1, f(2, f(3, z))).
The seed sits at the far right and the list is combined inward from the end.
// List(1, 2, 3).foldRight(0)(_ + _)
// = 1 + (2 + (3 + 0))
// = 6When Direction Matters
For associative, commutative operations like sum or product, both folds give the same answer.
For non-commutative operations like subtraction or list building, the direction changes the result. Choose deliberately.
val xs = List(1, 2, 3)
val l = xs.foldLeft(0)(_ - _) // ((0-1)-2)-3 = -6
val r = xs.foldRight(0)(_ - _) // 1-(2-(3-0)) = 2
@main def run(): Unit =
println((l, r)) // (-6, 2)Building a List
foldRight is the natural choice for rebuilding a list in order, because it works from the tail inward and prepending keeps elements in place.
This maps each element while preserving order.
val xs = List(1, 2, 3)
val doubled = xs.foldRight(List.empty[Int]) { (x, acc) =>
(x * 2) :: acc
}
@main def run(): Unit =
println(doubled) // List(2, 4, 6)foldLeft Reverses
If you build a list with foldLeft and prepend, the result comes out reversed, because elements are added front-first as you move rightward.
This is sometimes exactly what you want.
val xs = List(1, 2, 3)
val rev = xs.foldLeft(List.empty[Int]) { (acc, x) =>
x :: acc
}
@main def run(): Unit =
println(rev) // List(3, 2, 1)Stack Safety
foldLeft is tail recursive and runs as a loop, so it is safe on huge collections.
foldRight on a List is not tail recursive and can overflow the stack for very long lists. Prefer foldLeft when you do not need right-to-left order.
// Safe even for millions of elements:
val n = (1 to 1000000).foldLeft(0L)(_ + _)
// foldRight on a long List risks StackOverflowErrorChanging the Result Type
The accumulator type can differ from the element type.
Here we fold a list of ints into a string, so the seed is an empty string and each step appends.
The fold's type is driven by the seed.
val xs = List(1, 2, 3)
val s = xs.foldLeft("")((acc, x) => acc + x.toString)
@main def run(): Unit =
println(s) // "123"Fold as a Swiss Army Knife
Many list operations are special cases of fold: sum, product, length, max, map, filter, reverse.
Recognizing the fold underneath them helps you write concise, declarative code instead of hand-rolled recursion.
val xs = List(4, 1, 7, 3)
val maxV = xs.foldLeft(Int.MinValue)(_ max _)
val len = xs.foldLeft(0)((acc, _) => acc + 1)
@main def run(): Unit =
println((maxV, len)) // (7, 4)Quick Check
Reason about fold direction and the seed position.
Recap
foldLeft walks left to right with the accumulator on the left and computes ((z op a) op b) op c. It is tail recursive and stack safe.
foldRight walks right to left with the seed on the right and computes a op (b op (c op z)). It suits order-preserving list construction but can overflow on long lists.
The seed determines the result type, so folds can transform a collection into any value.
Sıkça Sorulan Sorular
“foldLeft ve foldRight” dersi ücretsiz mi?
Evet — “foldLeft ve foldRight” 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.
“foldLeft ve foldRight” dersinde ne öğreneceğim?
Koleksiyonları tek bir değere indirgeyin. 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 3. dersidir.
“foldLeft ve foldRight” 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
- Özyinelemeli Düşünme
- Birikim Kalıpları
- foldLeft ve foldRight
- reduce ve aggregate