Higher-Order Functions in Scala
Higher-order functions are functions that take other functions as parameters or return functions as results. They can be used to write concise and expressive code that is easy to read and understand. Here's an example of using a higher-order function to filter a list:
scss
val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
def filterList(list: List[Int], f: Int => Boolean): List[Int] = {
list.filter(f)
}
val evenNumbers = filterList(numbers, _ % 2 == 0)
println(s"The even numbers are $evenNumbers.")
val bigNumbers = filterList(numbers, _ > 5)
println(s"The big numbers are $bigNumbers.")
In this example, a filterList function is defined that takes a list of integers and a function f that takes an integer and returns a boolean. The filterList function applies the f function to each element of the list and returns a new list containing only the elements for which f returns
No comments:
Post a Comment