Book Image

Learning Functional Programming in Go

By : Lex Sheehan
Book Image

Learning Functional Programming in Go

By: Lex Sheehan

Overview of this book

Lex Sheehan begins slowly, using easy-to-understand illustrations and working Go code to teach core functional programming (FP) principles such as referential transparency, laziness, recursion, currying, and chaining continuations. This book is a tutorial for programmers looking to learn FP and apply it to write better code. Lex guides readers from basic techniques to advanced topics in a logical, concise, and clear progression. The book is divided into four modules. The first module explains the functional style of programming: pure functional programming, manipulating collections, and using higher-order functions. In the second module, you will learn design patterns that you can use to build FP-style applications. In the next module, you will learn FP techniques that you can use to improve your API signatures, increase performance, and build better cloud-native applications. The last module covers Category Theory, Functors, Monoids, Monads, Type classes and Generics. By the end of the book, you will be adept at building applications the FP way.
Table of Contents (21 chapters)
Title Page
Credits
About the Author
Acknowledgments
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface
Index

Iterating through a collection


In order to implement a collection, we must provide a way to access each element in the collection, which can be accomplished using the int index value shown in the following code. We will implement a first in, first out (FIFO) order queue. We will provide a way to store the elements using a slice data structure. Lastly, we will implement a Next() method to provide a way to traverse the elements in the collection.

In the following code, we define an interface for the Iterator object. It has one method, Next(), which will return the next element in the collection and a Boolean flag to indicate whether it's OK to continue iterating:

type CarIterator interface {
     Next() (value string, ok bool)
}
const INVALID_INT_VAL = -1
const INVALID_STRING_VAL = ""

Next, we define a collection object that has two properties: an int index used to access the current element and a slice of strings, that is, the actual data in the collection:

type Collection struct {
       index...