Go Higher Order Function

1. Introduction

A higher-order function is a function that takes one or more functions as parameters and/or returns a function as its result. This concept allows for function composition and functional programming techniques. This blog post will provide an example of a higher-order function in Go.

2. Program Steps

1. Define a function that will be passed as an argument to the higher-order function. This function will perform a simple calculation, like doubling a number.

2. Define the higher-order function that accepts another function and an integer as arguments. The higher-order function applies the passed-in function to the integer.

3. In the main function, invoke the higher-order function with the simple calculation function and an integer as arguments.

3. Code Program

package main

import "fmt"

// double is a simple function to demonstrate a calculation.
// It takes an integer and returns its double.
func double(num int) int {
	return num * 2
}

// apply is a higher-order function that takes a function and an int.
// It applies the function to the integer and returns the result.
func apply(function func(int) int, num int) int {
	return function(num)
}

func main() {
	number := 5
	// Using the higher-order function 'apply' with 'double' and an integer.
	result := apply(double, number)
	fmt.Printf("Applying double to %d gives %d\n", number, result)
}

Output:

Applying double to 5 gives 10

Explanation:

1. package main - This line establishes the package for our Go program.

2. import "fmt" - This line imports the Format package needed for printing output.

3. func double(num int) int - This line defines a function double that will be used to demonstrate an operation. It takes an integer and returns its double.

4. func apply(function func(int) int, num int) int - This line defines the higher-order function apply. It accepts a function and an integer, applies the function to the integer, and returns the result.

5. number := 5 - In the main function, we define a variable number with the value 5.

6. result := apply(double, number) - We then use the higher-order function apply, passing in the double function and the number variable.

7. fmt.Printf(...) - Finally, we print out the result of applying the double function to number, which gives us 10.

8. The output is "Applying double to 5 gives 10", confirming that our higher-order function works as expected.


Comments