Search⌘ K
AI Features

Solution Review: Write Your First Higher-Order Function

Understand how to write a higher-order function in Scala by creating a function that takes another function as input along with integers and prints the computed result. This lesson builds foundational skills in functional programming with Scala.

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.

Scala
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.