Solution Review: Write Your First Higher-Order Function

In the following lesson, we will go over the solution of the challenge: Write Your First Higher-Order Function.

We'll cover the following

Task

In this challenge, you had to create a function which prints the result of another function.

Solution

A skeleton of the function was already provided for you. Let’s look it over.

def arithmeticPrinter(f: (Int , Int) => Int, x: Int, y: Int) = {
 
}

The function name is arithmeticPrinter and it has three parameters. The first parameter is another function f which has two parameters of its own and returns an integer. The second parameter is an integer x and the third parameter is an integer y.

You had to write a line of code which would print the result of f given that it was passed x and y as arguments.

print(f(x,y))

You can find the complete solution below:

You were required to write the code on line 2.

Press + to interact
def arithmeticPrinter(f: (Int , Int) => Int, x: Int, y: Int) = {
print(f(x,y))
}
// Driver Code
def add(a:Int, b: Int) = {
a + b
}
arithmeticPrinter(add,4,9)

In the next lesson, we will learn about anonymous functions.