0Pricing
Scala for Backend Engineering & Functional Programming · 강의

foldLeft와 foldRight

컬렉션을 하나의 값으로 축약해 보세요.

foldLeft와 foldRight은(는) CoddyKit의 무료 Scala for Backend Engineering & Functional Programming 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Scala for Backend Engineering & Functional Programming 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Scala for Backend Engineering & Functional Programming 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

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.

자주 묻는 질문

“foldLeft와 foldRight” 강의는 무료인가요?

네 — “foldLeft와 foldRight” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Scala for Backend Engineering & Functional Programming 강의 전체를 잠금 해제할 수 있습니다. Scala for Backend Engineering & Functional Programming 강의에는 총 4개의 강의가 포함되어 있습니다.

“foldLeft와 foldRight”에서 뭘 배우나요?

컬렉션을 하나의 값으로 축약해 보세요. 브라우저에서 직접 실행하는 실습 코드로 Scala for Backend Engineering & Functional Programming을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Scala for Backend Engineering & Functional Programming을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Scala for Backend Engineering & Functional Programming은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“foldLeft와 foldRight” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Scala for Backend Engineering & Functional Programming 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Scala for Backend Engineering & Functional Programming 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 재귀적으로 사고하기
  2. 누산기 패턴
  3. foldLeft와 foldRight
  4. reduce와 집계
← Scala for Backend Engineering & Functional Programming(으)로 돌아가기