The reduce() method is a HOF that takes all the elements in a collection (Array, List, etc) and combines them using a binary operation to produce a single value.
Functional languages treat functions as first-class values.
This means that, like any other value, a function can be passed as a parameter and returned as a result.
This provides a flexible way to compose programs.
function that take other function as parameters or that return function as results are called higher-order function.
Advantages of Higher Order Functions
Programming with higher order functions, such as map
and foreach
, has a number of advantages:
- It is much easier to understand the program and the intention of the programmer is clearly expressed in the code.
- Functions which take Funs as arguments are much easier to re-use than other functions.
Anonymous Function
An anonymous function‘s is a functions literal. A function’s which deosn’t contain a name in a anonymous function’s. An anonymous function’s provides a lightweight function’s definition.
Simply the anonymous function’s mean without a name. These function’s are define as literal and are syntactic sugar for a more tedious long definition.
(b:Int)=>b
(b:Int)=>b*b
Anonymous is a that has no name but works as a function’s. It is good to create an anonymous function’s. when you don’t want to reuse it latter.
Function Currying
Currying allows us to apply some arguments to the function’s now and others at a later time when required.
Currying splits method with multiple parameters into a chain of functions, each with one parameter – basically its a method notation to write a partially applied in a better way.
def sum(f:Int=>Int):(Int,Int)=>Int={
def sumF(a:Int,b:Int):Int=
if(a>b) 0 elsef(a)+sumF(a+1,b)
sumF()
}
Functions that accept functions
The argument in the call are match one by one in the order of the parameters of the called function. Named arguments allow you to pass arguments in a different order.
CODE:
package NewCourse
object HOF{
def main(args:Array[String]): Unit = {
printInt(b=2,a=5);
}
def printInt(a:Int,b:Int): Unit = {
println("a:"+a)
println("b:"+b)
}
}
OUTPUT:
a:5
b:2
Example:
FunctionImplementations-


Conclusion:-
HOF describes “how” the work is to be complete in a collection.
Reference:-
https://www.geeksforgeeks.org/higher-order-functions-in-scala/