Back to Notes
August 29, 2023

Higher-Order Function Intro

A powerful tool that takes other functions as arguments or returns them as results, enabling more modular, reusable, and abstract code.


In programming, higher-order function is like a special tool. It is a function that can take other functions as arguments or return functions as the results, a higher-order function lets you work with functions in a clever way.

As an analogy, it’s similiar to a toolbox, in the toolbox you have basic tools such as hammer, screwdriver and so on, they’re like just regular functions. Then now, imagine you get a super tool that can take any of those basic tools functionalities and combine them in various ways to ceate new brand tools to perform complex tasks, that super tool is your higher order function.

So now you know, higher-order function is a powerful concept that allows you to treat functions like building blocks, composing them to solve more complex problems, and it makes your code more reusable, flexible and efficient.

The “higher-order” part refers to the fact that these functions operates other functions, making them one step “higher” in abstraction compared to regular functions in operating data, so they go beyond just dealing with values, they work with functions themselves.

The term “higher-order” might sound a bit technical, but it’s essentially describing the idea of functions working with other functions, which adds a layer of abstraction and flexibility to your code.

func mapInts(numbers []int, f func(int) int) []int {
	result := make([]int, len(numbers))
	for i, num := range numbers {
		result[i] = f(num)
	}
	return result
}

func main() {
	numbers := []int{1, 2, 3, 4, 5}

	// A function that doubles a number
    double := func(n int) int {
		return n * 2
	}
	
	// Use the mapInts to double every number in the slice above
	doubledNumbers := mapInts(numbers, double)

	// Print the original and doubled numbers
	fmt.Println("Original numbers:", numbers)
	fmt.Println("Doubled numbers:", doubledNumbers)
}

Implementing higher-order functions gives you several important benefits that can lead to more modular, flexible, and reusable code.

In essence, higher-order functions empower you to work at a higher level of abstraction, enabling you to build more sophisticated and maintainable software. They are a fundamental tool in functional programming paradigms and are widely used to create elegant and efficient code.