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

Preface

Until recently, the message has been Go and functional programming—don't do it.

Functional programming (FP) is a perfect fit for multicore, parallel processing. Go is a concurrency baller (with Goroutines, channels, and so on) and already runs on every available CPU core. FP reduces complexity; simplicity is one of Go's biggest strengths. 

So, what can FP bring to Go that will actually improve our software applications? Here's what it offers:

  • Composition: FP shows us how to decompose our apps and rebuild them by reusing small building blocks.
  • Monads: Using monads, we are able to safely order our workflows into pipelines of data transformations.
  • Error handling: We can leverage monadic error handling and still maintain compatibility with idiomatic Go code.
  • Performance: Referential transparency is where we can evaluate our function once and then subsequently refer to its pre-computed value.
  • Expressive code: FP allows us to concisely express business intent in our code. We declare what our functions do, without the clutter of error checking after every function call, and without having to follow state changes (pure FP means immutable variables).
  • Simpler code: No shared data means not having to deal with semaphores, locks, race conditions, or deadlocks.

Most people have difficulty grasping FP.

I did too. And when I got it, I wrote this book. Take this journey with me. We'll see hundreds of illustrations, read easy-to-understand explanations, and implement FP in Go code along the way.

I enjoyed coaching soccer. The litmus test I used to determine whether I succeeded as a coach was the answer to this simple question: Did they all register for next season and request me to be their coach? Just like planning practice, I planned each chapter, starting with simple concepts and adding to them. Read this book, then you too will be able to say, I got it.

If you want to improve your FP skills, this book is for you.

 

What this book covers

Chapter 1, Pure Functional Programming in Go, introduces the declarative style of programming and demonstrates recursion, memorization, and Go's concurrency constructs using the Fibonacci Sequence. We will learn how to benchmark/performance test your recursive code and we will get some bad news.

Chapter 2, Manipulating Collections, shows us how to use intermediate (Map, Filter, and Sort) and terminal (Reduce, GroupBy, and Join) functions to perform data transformations. We use a Mocha-like BDD Go framework to test predicate functions. Itertools helps us grasp the breadth of FP collection manipulating function and we look at a distributed MapReduce solution: Gleam = Go + LuaJIT + Unix Pipes.

Chapter 3, Using High-Order Functions, covers a list of 27 FP characteristics: Anonymous function, closures, currying, Either data type, first-class functions, functions, functional composition, Hindley-Milner type system, Idempotence, immutable state, immutable variables, Lambda expressions, List Monad, Maybe data type, Maybe Monad, Monadic error, handling, No side-effects, operator overloading, option type, parametric polymorphism, partial function application, recursion, referential transparency, sum or union types, Tail Call Optimization, typeclasses, and Unit type. It also covers an example of Generics, and illustrates its value to FP programmers. We implement the Map, Filter, and Reduce functions, as well as lazy evaluation using Goroutines and a Go channel.

Chapter 4, SOLID Design in Go, talks about why Gophers loath Java, principles of good software design, how to apply the Single Responsibility principle, function composition, the open/closed Principle, FP contracts, and duck typing. It also covers how to model behavior using interfaces, compose software using the Interface Segregation principle and embedded interfaces. We will learn about the law of Associativity with a purple Monoid chain and get the big reveal—Monads chain continuations.

Chapter 5, Adding Functionality with Decoration, illustrates interface composition using Go's complimentary Reader and Writer interfaces. Next, we will learn how procedural design compares to functional Inversion of Control. We will implement the following decorators: authorization, logging, and load balancing. Also, we will add easy-metrics to our app to see our decorator pattern in action.

Chapter 6, Applying FP at the Architectural Level, builds an application framework using a layered architecture, which solves cyclical dependency errors. We will learn how to apply the Hollywood principle and the difference between the observer pattern and dependency injection. We will use Inversion of Control (IoC) to control the flow of logic and build a layered application. Also, we will build an effective table-driven framework to test our application's API.

Chapter 7, Functional Parameters, enlightens us as to why a lot of  we've learned from Java and object-oriented programming does not apply to Go, teaches us a better way to refactor long parameter lists using functional options, and helps us understand the difference between currying and partial application. We will learn how to apply partial application to create another function with a smaller arity. We will use a context to gracefully shut down our server and see  how to cancel and roll back a long-running database transaction using a context.

Chapter 8, Increase Performance Using Pipelining, covers data flow types (Read, Split, Transform, Merge, and Write) and teaches us when and how to build a data transformation pipeline. We use buffering to increase throughput, goroutines and channels to process data faster, improve API readability using interfaces, and implement some useful filters. We also implement and compare imperative and functional pipeline designs for processing credit card charges.

Chapter 9, Functors, Monoids, and Generics, gives us an appreciation for the lack of support for Generics in Go. We will see how to use a code generation tool to solve the repetitive boilerplate code problem. We will dive deep into function composition, implement a few functors, and learn how to map between worlds. We will also learn how to write a Reduce function to implement an invoice processing monoid.

Chapter 10, Monads, Type Classes, and Generics, shows us how a Monad works and teaches us how to compose functions using the Bind operation. It shows us how Monads process errors and deal with Input/Output (I/O). This chapter works through a monadic workflow implementation in Go. We cover what The Lambda Calculus is and what it has to do with Monads, see how The Lambda Calculus implements Recursion, and learn how the Y-Combinator works in Go. Next, we use the Y-Combinator to control a workflow and learn how to handle all errors at the end of the pipe. We will learn how type classes work and implement a few in Go. Finally, we review the pros and cons of generics in Go.

Chapter 11Category Theory That Applies, gives us a working understanding of category theory. We will learn to appreciate the deep connection between category theory, logic, and type theory. We will increase our understanding with a journey through the history of FP. This chapter uses a Venn diagram to help explain various categories of programming languages. We come to understanding of what binding, currying, and application mean in the context of a lambda expression. This chapter shows us that the Lambda Calculus is like chocolate milk. This chapter covers the type system implications of FP, shows us different categories of homomorphisms and when to use them, and uses mathematics and the flight of a soccer ball to increase our understanding of morphisms. We will cover function composition with linear and quadratic functions, and we will learn about interface-driven development. We'll explore the value in knowledge-driven systems, and we will learn how to apply our understanding of category theory to build better applications.

Appendix, Miscellaneous Information and How-Tos, shows us how the author suggests that we build and run the Go projects in this book. It shows us how to propose changes to Go, introduces the Lexical Workflow Solution: a Go-compatible way to handle errors in one place, provides a place to go to provide feedback and an FP resources page, discusses the Minggatu-Catalan Number, and offers a solution for world peace.

What you need for this book

If you want to run the Go projects discussed in each chapter, you need to install Go. Next, you need to get your Go development environment running and start writing code.

Read  the TL;DR subsection of the How to build and run Go projects section of the Appendix. Go  to Chapter 1Pure Functional Programming in Go in the book and start reading the Getting the source code section. Continue  reading on how to set up and run your first project.

Other Go resources include:

Note

When I think of other things to add, I'll put that information here: https://lexsheehan.blogspot.com/2017/11/what-you-need-for-this-book.html.

Who this book is for

A lot of the information in this book requires only a high school education.

For the programming sections in this book, you should have at least one year programming experience. Proficiency with Go or Haskell is ideal, but experience with other languages such as C/C++, Python, Javascript, Java, Scala or Ruby is also sufficient. You should have some familiarity using the command line.

This book should appeal to two groups:

  1. Non-programmers (read Chapter 11, Category Theory That Applies) If you are one of these:
  • K-12 math teacher and want to see why what you are teaching matters
  • Math teacher and want to see how what you are teaching relates to other branches of mathematics
  • Student in law school and want to understand what you will be doing when you plead your client’s case
  • Soccer enthusiast and like math
  • Person interested in learning category theory
  • Lover of the Lambda Calculus and want to see it illustrated with diagrams, pictures, and Go code
  • Manager of software projects and want to see a better correspondence between requirement gathering, implementation, and testing
  • C-level executive and want to understand what motivates and excites your IT staff
  1. Programmers: If you are one of these:
  • Software enthusiast and want to learn Functional Programming
  • Software tester and want to see a better correspondence between requirement gathering, implementation, and testing
  • Software architect and want to understand how to use FP
  • Go developer and like soccer
  • Go developer and want to implement your business use case programming tasks with more expressive code
  • Go developer and want to understand Generics
  • Java developer and would like to understand why we say, less is more
  • Your_language_here developer who knows FP and wants to transfer your skills to Go
  • Go developer looking for a better way to build data transformation pipelines
  • Go developer and would like to see a viable way to write less code, that is, fewer if err != nil blocks
  • Experienced Go developer and want to learn FP or add some tools to your toolbox
  • Person involved in software development and want to understand any of the terms below.

If you are a Go developer looking for working code, with line-by-line explanations for any of the following, this book is for you:

  • Benchmark testing
  • Concurrency (Goroutines/Channels)
  • Currying
  • Data transformation pipeline
  • Decorator Pattern
  • Dependency Injection
  • Duck typing
  • Embedding Interfaces
  • Error handler
  • Function composition
  • Funcitonal parameters
  • Functors
  • Generics via code generation
  • Hollywood Principle
  • Interface-driven development
  • I18N (language translation)
  • IoC
  • Lambda expressions in Go
  • Layered application framework
  • Log handler
  • Monads
  • Monoids
  • Observer Pattern
  • Partial application
  • Pipeline to process credit card payments
  • Recursion
  • Reduce function to sum invoice totals
  • Solve circular dependency errors
  • Table-driven http API test framework
  • Type Class
  • Upload/download files to/from Google Cloud Buckets
  • Y-Combinator

Note

If I decide to change the format or update this info, I'll put it here: http://lexsheehan .blogspot.com/2017/11/who-this-book-is-for.html.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning. Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "We update code, run the glide-update and go-run commands, and repeat until done." A block of code is set as follows:

func newSlice(s []string) *Collection {
  return &Collection{INVALID_INT_VAL, s}
}

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

[default] 
exten => s,1,Dial(Zap/1|30) 
exten => s,2,Voicemail(u100) 
exten => s,102,Voicemail(b100)
exten => i,1,Voicemail(s0) 

Any command-line input or output is written as follows:

go get --help

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "In order to download new modules, we will go to Files | Settings | Project Name | Project Interpreter."

Note

Warnings or important notes appear like this.

Note

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you. You can download the code files by following these steps:

  1. Log in or register to our website using your e-mail address and password.
  2. Hover the mouse pointer on the SUPPORT tab at the top.
  3. Click on Code Downloads & Errata.
  4. Enter the name of the book in the Search box.
  5. Select the book for which you're looking to download the code files.
  1. Choose from the drop-down menu where you purchased this book from.
  2. Click on Code Download.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR / 7-Zip for Windows
  • Zipeg / iZip / UnRarX for Mac
  • 7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Learning-Functional-Programming-in-Go. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/LearningFunctionalProgramminginGo_ColorImages.pdf.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy. Please contact us at [email protected] with a link to the suspected pirated material. We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.