Book Image

Functional Programming in Go

By : Dylan Meeus
Book Image

Functional Programming in Go

By: Dylan Meeus

Overview of this book

While Go is a multi-paradigm language that gives you the option to choose whichever paradigm works best for the particular problem you aim to solve, it supports features that enable you to apply functional principles in your code. In this book, you’ll learn about concepts central to the functional programming paradigm and how and when to apply functional programming techniques in Go. Starting with the basic concepts of functional programming, this Golang book will help you develop a deeper understanding of first-class functions. In the subsequent chapters, you’ll gain a more comprehensive view of the techniques and methods used in functional languages, such as function currying, partial application, and higher-order functions. You’ll then be able to apply functional design patterns for solving common programming challenges and explore how to apply concurrency mechanisms to functional programming. By the end of this book, you’ll be ready to improve your code bases by applying functional programming techniques in Go to write cleaner, safer, and bug-free code.
Table of Contents (17 chapters)
1
Part 1: Functional Programming Paradigm Essentials
7
Part 2: Using Functional Programming Techniques
11
Part 3: Design Patterns and Functional Programming Libraries

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...