コレクションに対する関数型操作
データ変換に使うmap、filter、fold、reduceなど、一般的な関数型操作を使いこなします。
「コレクションに対する関数型操作」はCoddyKit上の無料Scala for Backend Engineering & Functional Programmingレッスンです。 これはレッスン2/3です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはScala for Backend Engineering & Functional Programming学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Scala for Backend Engineering & Functional Programmingコースには全3レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
Functional Ops: Why Use Them?
Functional operations on collections help you transform and combine data without changing the original collection. This approach promotes immutability and makes your code easier to read and test.
We'll explore key operations like map, filter, reduce, and fold.
Transform with `map`
The map operation applies a function to each element of a collection and returns a new collection with the transformed results. The original collection remains unchanged.
Try running this example:
object Main {
def main(args: Array[String]): Unit = {
val numbers = List(1, 2, 3, 4)
val doubled = numbers.map(n => n * 2)
println(s"Original: $numbers")
println(s"Doubled: $doubled")
}
}`map` with Different Types
map is very flexible! You can transform elements into a completely different type. Here, we convert numbers to strings, or get string lengths.
Notice how the result is a List[Int], even though the input was List[String].
object Main {
def main(args: Array[String]): Unit = {
val names = List("Alice", "Bob", "Charlie")
val lengths = names.map(name => name.length)
println(s"Names: $names")
println(s"Lengths: $lengths")
}
}Select with `filter`
The filter operation creates a new collection containing only the elements that satisfy a given condition (a predicate function). It "filters out" unwanted elements.
Let's find the even numbers:
object Main {
def main(args: Array[String]): Unit = {
val numbers = List(1, 2, 3, 4, 5, 6)
val evens = numbers.filter(n => n % 2 == 0)
println(s"Original: $numbers")
println(s"Evens: $evens")
}
}More `filter` Examples
You can use any boolean expression as your filter condition. Let's filter a list of words to keep only those longer than 4 characters.
object Main {
def main(args: Array[String]): Unit = {
val words = List("apple", "cat", "banana", "dog", "elephant")
val longWords = words.filter(w => w.length > 4)
println(s"Words: $words")
println(s"Long words: $longWords")
}
}Combine with `reduce`
The reduce operation combines all elements of a collection into a single result. It takes a binary operation (a function that takes two arguments and returns one) and applies it cumulatively.
Here, we sum all elements:
object Main {
def main(args: Array[String]): Unit = {
val numbers = List(1, 2, 3, 4)
val sum = numbers.reduce((a, b) => a + b)
println(s"Numbers: $numbers")
println(s"Sum: $sum")
}
}`reduce` for Product & Max
reduce can perform various aggregations. We can calculate the product of numbers or find the maximum value.
Note: reduce will throw an error on an empty collection.
object Main {
def main(args: Array[String]): Unit = {
val numbers = List(1, 5, 2, 8)
val product = numbers.reduce((a, b) => a * b)
val maxNum = numbers.reduce((a, b) => if (a > b) a else b)
println(s"Numbers: $numbers")
println(s"Product: $product")
println(s"Max: $maxNum")
}
}`fold`: Initial Value Power
fold is similar to reduce but with an important difference: it takes an initial value (also called an "accumulator"). This makes it safe for empty collections and allows for different result types.
Let's sum numbers, starting from 10:
object Main {
def main(args: Array[String]): Unit = {
val numbers = List(1, 2, 3)
// foldLeft(initialValue)(operation)
val sumWithInitial = numbers.foldLeft(10)((acc, n) => acc + n)
println(s"Numbers: $numbers")
println(s"Sum (starting from 10): $sumWithInitial")
}
}Direction: `foldLeft` vs `foldRight`
Scala offers foldLeft and foldRight. They differ in the order of processing elements and how the accumulator is passed.
foldLeft(initial)(op): Processes left-to-right.foldRight(initial)(op): Processes right-to-left.
For operations like string concatenation, the direction matters!
object Main {
def main(args: Array[String]): Unit = {
val chars = List('a', 'b', 'c')
val leftFold = chars.foldLeft("")((acc, c) => acc + c)
val rightFold = chars.foldRight("")((c, acc) => acc + c)
println(s"Chars: $chars")
println(s"foldLeft: $leftFold") // Output: abc
println(s"foldRight: $rightFold") // Output: abc (due to string append order)
// Example where order matters: (acc, char) => char + acc
val rightFoldReversed = chars.foldRight("")((c, acc) => c + acc)
println(s"foldRight (char + acc): $rightFoldReversed") // Output: abc
// A common example where order matters is for operations like subtraction or division, but string concatenation also shows it.
}
}Functional Operations Check
Consider the following Scala code snippet:
val data = List(10, 20, 30, 40)
val result1 = data.map(x => x / 10)
val result2 = data.filter(x => x > 25)
val result3 = data.reduce((a, b) => a + b)
Which of the following statements are TRUE about the results?
Recap: Power of Functional Ops
You've mastered essential functional operations!
maptransforms each element.filterselects elements based on a condition.reducecombines elements into a single result (requires non-empty collection).foldcombines elements with an initial value (safe for empty collections).
These operations are key for writing concise, immutable, and powerful Scala code. Next, we'll explore robust error handling using Option, Try, and Either.
よくある質問
「コレクションに対する関数型操作」レッスンは無料ですか?
はい。「コレクションに対する関数型操作」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Scala for Backend Engineering & Functional Programmingコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Scala for Backend Engineering & Functional Programmingコースには全3レッスンが含まれています。
「コレクションに対する関数型操作」で何を学びますか?
データ変換に使うmap、filter、fold、reduceなど、一般的な関数型操作を使いこなします。 ブラウザで直接実行するハンズオンコードでScala for Backend Engineering & Functional Programmingを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Scala for Backend Engineering & Functional Programmingを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのScala for Backend Engineering & Functional Programmingは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン2/3です。
「コレクションに対する関数型操作」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このScala for Backend Engineering & Functional Programmingレッスンでコードを書いて実行できますか?
はい。すべてのScala for Backend Engineering & Functional Programmingレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- 不変コレクション詳解
- コレクションに対する関数型操作
- エラー処理のためのOption、Try、Either