Lesson 11 of 15
Higher-Order Functions
Higher-Order Functions
Functions can take other functions as parameters:
def applyTwice(f: Int => Int, x: Int): Int = f(f(x))
println(applyTwice(x => x * 2, 3)) // 12
Returning Functions
def multiplier(factor: Int): Int => Int = x => x * factor
val triple = multiplier(3)
println(triple(5)) // 15
reduce
reduce is like foldLeft but uses the first element as the starting value:
val product = List(1, 2, 3, 4).foldLeft(1)((acc, x) => acc * x)
println(product) // 24
Your Task
Write a function product that takes a List[Int] and returns the product of all elements using foldLeft. An empty list should return 1.
JS Transpiler loading...
Loading...
Click "Run" to execute your code.