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

Type classes


Type classes allow us to define behavior on types.

As discussed in Chapter 3, Using High-Order Functions, type classes add an additional layer to our type system.

We accomplish this by:

  1. Defining behavior using Go interfaces (parent type class)
  2. Declaring a new type (base type class) to wrap base types
  3. Implementing behavior on our new type classes

Let’s look at our Equals type class implementation.

Parent class definition:

//4-purely-functional/ch11-monads/05_typeclasss/src/typeclass/equals.go
package typeclass

import (
"strconv"
)
type Equals interface {
   Equals(Equals) bool
}

Equals is our parent type class. All base classes must implement the Equals method.

Base class definitions

We'll define two base types, Int and String.

Int base class

The Equals method of Int will check whether other types are equal, using whatever logic we deem appropriate:

type Int int

func (i Int) Equals(e Equals) bool {
   intVal := int(i)
switch x := e.(type) {
case Int:
return intVal == int(x)
case String:...