Higher order functions are functions which receive a function as input or return a function as output. This is very useful in functional programming. This helps with code readability.

Function as Parameter

Below is an example in which calc function takes another function as an argument. This creates a very interesting reading code. In this case, calc is called higher order function. I can also pass an anonymous function into this function as we are doing for the subtraction variable.

Example:

 1package main
 2
 3import "fmt"
 4
 5func main() {
 6	addition := calc(5, 2, add)
 7	fmt.Println("Addition:", addition)
 8
 9	subtraction := calc(5, 1, func(a int, b int) int {
10		return a - b
11	})
12	println("Subtraction:", subtraction)
13}
14
15func calc(a int, b int, calculation func(int, int) int) int {
16	return calculation(a, b)
17}
18
19func add(a int, b int) int {
20	return a + b
21}

In this case, calc function can take any function that takes two int arguments and returns an int value. This way we can perform various mathematical operation by passing different function into it.

Output:

Addition: 7
Subtraction: 4

Function as a Return Value

We have already seen examples of functions which return function as output.

 1package main
 2
 3import "fmt"
 4
 5func main() {
 6	fmt.Println("Sum of 1 and 2 is", sum(1, 2)())
 7}
 8
 9func sum(a int, b int) func() int {
10	return func() int {
11		return a + b
12	}
13}

In this case, the function call on line 6 looks slightly strange: sum(1,2)(). We are using parentheses twice here.

Output:

Sum of 1 and 2 is 3