0Pricing
Scala for Backend Engineering & Functional Programming · Lektion

foldLeft und foldRight

Reduzieren Sie Collections auf einen Wert.

foldLeft und foldRight ist eine kostenlose Scala for Backend Engineering & Functional Programming-Lektion auf CoddyKit. Dies ist Lektion 3 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Scala for Backend Engineering & Functional Programming-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Scala for Backend Engineering & Functional Programming-Kurs umfasst insgesamt 4 Lektionen.

Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.

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)  // 10

How 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
// = 6

foldRight 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)  // 10

How 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))
// = 6

When 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 StackOverflowError

Changing 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.

Häufig gestellte Fragen

Ist die Lektion „foldLeft und foldRight“ kostenlos?

Ja — der vollständige Text von „foldLeft und foldRight“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Scala for Backend Engineering & Functional Programming-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Scala for Backend Engineering & Functional Programming-Kurs umfasst insgesamt 4 Lektionen.

Was lerne ich in „foldLeft und foldRight“?

Reduzieren Sie Collections auf einen Wert. Du übst Scala for Backend Engineering & Functional Programming mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.

Brauche ich Erfahrung, um Scala for Backend Engineering & Functional Programming zu starten?

Keine Vorkenntnisse erforderlich. Scala for Backend Engineering & Functional Programming auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 3 von 4.

Wie lange dauert die Lektion „foldLeft und foldRight“?

Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.

Kann ich in dieser Scala for Backend Engineering & Functional Programming-Lektion Code schreiben und ausführen?

Ja. Jede Scala for Backend Engineering & Functional Programming-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.

Alle Lektionen in diesem Kurs

  1. Rekursiv denken
  2. Akkumulator-Muster
  3. foldLeft und foldRight
  4. reduce und aggregate
← Zurück zu Scala for Backend Engineering & Functional Programming