1. Introduction
In functional programming, map and flatMap are two essential higher-order functions that transform collections. The map function takes a function as an argument and applies it to each element of the collection, returning a new collection. On the other hand, flatMap is similar but is used to flatten results. In this post, we'll implement custom versions of map and flatMap for a list in Scala.
2. Program Steps
1. Initialize the Scala environment.
2. Define the custom map and flatMap functions for a list.
3. Test the custom functions with sample lists and transformation functions.
4. Execute the program.
3. Code Program
object CustomMapFlatMap {
def main(args: Array[String]): Unit = {
val numbers = List(1, 2, 3, 4, 5)
// Using custom map function
val squaredNumbers = customMap(numbers, (x: Int) => x * x)
println(s"Squared Numbers: $squaredNumbers")
// Using custom flatMap function
val rangeList = customFlatMap(numbers, (x: Int) => List.range(1, x + 1))
println(s"Range List: $rangeList")
}
// Custom map function
def customMap[A, B](list: List[A], f: A => B): List[B] = {
list match {
case head :: tail => f(head) :: customMap(tail, f)
case Nil => Nil
}
}
// Custom flatMap function
def customFlatMap[A, B](list: List[A], f: A => List[B]): List[B] = {
list match {
case head :: tail => f(head) ::: customFlatMap(tail, f)
case Nil => Nil
}
}
}
Output:
Squared Numbers: List(1, 4, 9, 16, 25) Range List: List(1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5)
Explanation:
1. We start by defining an object CustomMapFlatMap containing our main method, and the custom implementations of map and flatMap functions.
2. The customMap function is a recursive function that applies the passed function f to each element of the list. It's defined for generic types, allowing it to work with any list type and transformation function.
3. The customFlatMap function is also recursive. It applies the passed function f to each element, expecting a list in return, and concatenates (:::) the results, effectively flattening them.
4. In the main method, we test the custom functions. First, we square each number in a list using the customMap function. Then, for each number in the list, we generate a range from 1 up to that number using the customFlatMap function.
5. The outputs show the transformed lists, demonstrating the functionality of our custom map and flatMap implementations.
Comments
Post a Comment