To demonstrate with a simple example, let's look at how we might define a first order function that takes two integer values and returns the sum of both values squared.

def sumOfSquares(a: Int, b: Int): Int = { a * a + b * b }

Next, let's look at how we could refactor this to use a higher-order function. Here is a function that takes 3 parameters:

- a function that takes an Int and returns an Int
- an Int named a
- an Int named b

def sumOfTwoOperations(f: Int => Int, a: Int, b: Int): Int = { f(a) + f(b) }

Next, let's call the sumOfTwoOperations function, passing a "squared" function as the first parameter.

def squared(x: Int): Int = x * x val result = sumOfTwoOperations(squared, 2, 5) // result = 29

The beauty of higher-order functions is that now we can define another operation, such as "cubed", and pass that to the sumOfTwoOperations.

def cubed(x: Int): Int = x * x * x val result = sumOfTwoOperations(cubed, 2, 5) // result = 133

## No comments:

## Post a Comment