0Pricing
Scala for Backend Engineering & Functional Programming · Ders

Katlama ve İndirgeme

foldLeft ve reduce

Katlama ve İndirgeme, 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.

Combining elements into one

Sometimes you need to combine all elements of a collection into a single value, like a sum or a concatenation. Scala provides fold, foldLeft, foldRight, and reduce for this.

object Main {
  def main(args: Array[String]): Unit = {
    val nums = List(1, 2, 3, 4)
    println(nums.sum)
    println(nums.product)
  }
}

reduce: combine without a seed

reduce combines elements pairwise using a binary function. It needs at least one element, otherwise it throws an exception.

object Main {
  def main(args: Array[String]): Unit = {
    val nums = List(1, 2, 3, 4)
    val total = nums.reduce((a, b) => a + b)
    println(total)
    val max = nums.reduce((a, b) => if (a > b) a else b)
    println(max)
  }
}

foldLeft: combine with a seed

foldLeft takes an initial seed value and a function. It is safe on empty collections (returns the seed) and lets the result type differ from the element type.

Syntax: xs.foldLeft(seed)((acc, x) => ...).

object Main {
  def main(args: Array[String]): Unit = {
    val nums = List(1, 2, 3, 4)
    val sum = nums.foldLeft(0)((acc, x) => acc + x)
    println(sum)
    val empty = List.empty[Int].foldLeft(0)(_ + _)
    println(empty)
  }
}

The accumulator pattern

In a fold, the first argument is the accumulator that carries the running result, and the second is the current element. Each step updates the accumulator.

object Main {
  def main(args: Array[String]): Unit = {
    val words = List("Scala", "is", "great")
    val sentence = words.foldLeft("")((acc, w) => acc + w + " ")
    println(sentence.trim)
  }
}

Result type can differ

A powerful feature of foldLeft: the accumulator type can differ from the elements. Here we fold a list of numbers into a String.

object Main {
  def main(args: Array[String]): Unit = {
    val nums = List(1, 2, 3)
    val joined = nums.foldLeft("nums:")((acc, n) => acc + " " + n)
    println(joined)
  }
}

foldRight: from the right

foldRight processes elements from right to left. The accumulator is the second argument: (x, acc) => .... Direction matters for non-commutative operations.

object Main {
  def main(args: Array[String]): Unit = {
    val nums = List(1, 2, 3, 4)
    val left = nums.foldLeft("")((acc, x) => acc + x)
    val right = nums.foldRight("")((x, acc) => acc + x)
    println("foldLeft:  " + left)
    println("foldRight: " + right)
  }
}

Left vs right and performance

foldLeft is tail-recursive and stack-safe on large lists. foldRight on a List can overflow the stack for very large inputs. Prefer foldLeft unless order forces otherwise.

object Main {
  def main(args: Array[String]): Unit = {
    val big = (1 to 100000).toList
    val total = big.foldLeft(0L)((acc, x) => acc + x)
    println(total)
  }
}

Building a collection with fold

Folds are general enough to build collections. Here we reverse a list by prepending each element to an accumulator list.

object Main {
  def main(args: Array[String]): Unit = {
    val nums = List(1, 2, 3, 4)
    val reversed = nums.foldLeft(List.empty[Int])((acc, x) => x :: acc)
    println(reversed)
  }
}

reduceOption for safety

Because reduce fails on empty collections, reduceOption returns an Option instead: Some(result) when non-empty, None when empty.

object Main {
  def main(args: Array[String]): Unit = {
    println(List(3, 1, 4).reduceOption(_ + _))
    println(List.empty[Int].reduceOption(_ + _))
  }
}

fold: a symmetric variant

fold is like foldLeft but the accumulator must be the same type as the elements. It is often used with parallel collections.

object Main {
  def main(args: Array[String]): Unit = {
    val nums = List(1, 2, 3, 4)
    val total = nums.fold(0)(_ + _)
    println(total)
  }
}

Counting with foldLeft

Folds can compute richer results, like counting how many elements satisfy a condition, all in one pass.

object Main {
  def main(args: Array[String]): Unit = {
    val nums = List(4, 7, 2, 9, 6, 1)
    val evenCount = nums.foldLeft(0)((acc, x) => if (x % 2 == 0) acc + 1 else acc)
    println(s"even numbers: $evenCount")
  }
}

Quick Check

What is the key difference between reduce and foldLeft?

Recap

You learned folding and reducing:

  • reduce — combine pairwise, no seed, fails if empty
  • reduceOption — safe variant returning Option
  • foldLeft — seed + accumulator, stack-safe, flexible result type
  • foldRight — right-to-left, watch the stack on large lists
  • Folds can even build new collections

Sıkça Sorulan Sorular

“Katlama ve İndirgeme” dersi ücretsiz mi?

Evet — “Katlama ve İndirgeme” 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.

“Katlama ve İndirgeme” dersinde ne öğreneceğim?

foldLeft ve reduce 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.

“Katlama ve İndirgeme” 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

  1. List, Vector, Set, Map
  2. Dönüşümler
  3. Katlama ve İndirgeme
  4. Gruplama ve Sıralama
← Scala for Backend Engineering & Functional Programming Sayfasına Dön