Challenge: Write your First Higher-Order Function
Test yourself and implement what you have learned so far in this challenge.
We'll cover the following...
Problem Statement
You need to create a higher-order function arithmeticPrinter which prints the result of an arithmetic function that has two parameters of type Int and returns a value of type Int.
In this challenge, you will assume that the following arithmetic functions have been declared:
def add(a: Int, b: Int): Int = {
a + b
}
def subtract(a:Int, b:Int) = {
a - b
}
def multiply(a:Int, b:Int) = {
a * b
}
def divide(a:Int, b:Int) = {
a / b
}
For instance, the arithmeticPrinter will take the add function as input and print its result.
Input
arithmeticPrinter has three parameters.
- A function
fwhich has two parameters of typeIntand returns a value of typeInt. - An integer
x - An integer
y
The input will be a function and two integers that will be passed to the function.
Output
The output will be the result of the arithmetic function.
Sample Input
add, 4, 9
Sample Output
13
Test Yourself
Write your code in the given area. Try the exercise by yourself first, but if you get stuck, the solution has been provided. Good luck!
def arithmeticPrinter(f: (Int , Int) => Int, x: Int, y: Int) = {print(" ") // Write your own code in the print statement}
Let’s go over the solution review in the next lesson.