Higher order functions
Higher order functions return functions as a result
def sumInts(a: Int, b: Int): Int = if (a > b) 0 else a + sumInts(a + 1, b)
- Higher order functions also take other functions as parameters
def sum(f: Int => Int, a: Int, b: Int): Int = if (a > b) 0 else f(a) + sum(f, a + 1, b)
def cube(x: Int): Int = x * x * x
We can write:
def sumInts(a: Int, b: Int) = sum(id, a, b)
Function types
Type A => B is the type of a function that takes an argument of type A and returns a result of type B
Anonymous functions
Anonymous functions are functions without names
(x: Int, y: Int) => x + y
(x: Int, y: Int) is the parameter of the function, and x + y is its body.
The type of the parameter can be omitted
Examples
Ex1: Write a function that takes the product of all the integers on a given interval
def productInts(a: Int, b: Int): Int = if (a > b) 1 else a * productInts(a + 1, b) productInts(1, 4)
Ex2: Write a function that takes the product of the factorials of all the integers on a given interval
def fact(x: Int): Int = if (x == 0) 1 else x * fact(x - 1) def productFactorials(a: Int, b: Int): Int = if (a > b) 1 else fact(a) * productFactorials(a + 1, b) productFactorials(2, 3)
Ex3: Write a general function which generalizes both sum and product
def mapReduce(f: Int => Int, compose: (Int, Int) => Int, zero: Int, a: Int, b: Int): Int = { if(a > b) zero else compose(f(a), mapReduce(f, compose, zero, a + 1, b)) } def sumCubes(a: Int, b: Int): Int = mapReduce(cube, sum, 0, a, b) def cube(x: Int): Int = x * x * x def sum(x: Int, y: Int): Int = x + y def product(x: Int, y: Int): Int = x * y sumCubes(2, 3)