Complete the code to declare a higher-order function that takes a function as a parameter.
fun operateOnNumber(x: Int, operation: (Int) -> Int): Int {
return operation([1])
}The parameter operation is a function that takes an Int and returns an Int. We call it with x inside the function.
Complete the code to declare a higher-order function that returns a function.
fun makeMultiplier(factor: Int): (Int) -> Int {
return [1](number: Int) = number * factor
}val instead of fun to declare the function.fun keyword.The function makeMultiplier returns another function. Using fun declares an anonymous function to return.
Fix the error in the higher-order function declaration that takes two functions as parameters.
fun combineOperations(x: Int, op1: (Int) -> Int, op2: (Int) -> Int): Int {
return op2(op1([1]))
}op1 itself instead of its argument.x.The function combineOperations applies op1 to x, then op2 to the result. So x must be passed to op1.
Fill both blanks to declare a higher-order function that takes a function and returns a function.
fun transformFunction(f: (Int) -> Int): (Int) -> Int {
return [1](x: Int) = f(x) + [2]
}val instead of fun.1 to the result.We declare an anonymous function with fun that takes x and returns f(x) + 1. The 1 is added to the result.
Fill all three blanks to declare a higher-order function that takes a function and returns a function that applies it twice.
fun twice(f: (Int) -> Int): (Int) -> Int {
return [1](x: Int) = f(f([2])) + [3]
}val instead of fun.x to f.0.The function twice returns an anonymous function declared with fun. It applies f twice to x and adds 0 (no change).