Example 1 – map dispatcher
One pattern that is enabled by these types of first-class functions is the “map dispatcher pattern.” This is a pattern where we use a map of “key to function.”
Creating a simple calculator
For this first example, let’s build a really simple calculator. This is just to demonstrate the idea of dispatching functions based on a certain input value. In this case, we are going to build a calculator that takes two integers as input, an operation, and returns the result of this operation to the user. For this first example, we are only supporting the addition, subtraction, multiplication, and division operations.
First, let’s define the basic functions that are supported:
func add(a, b int) int { return a + b } func sub(a, b int) int { return a - b } func mult(a, b int) int { return a + b } func div(a, b int) int { if b == 0 { panic("divide by zero") } return a / b }
So far, this is...