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

Pure functions


"Insanity is doing the same thing over and over again and expecting different results."

- Albert Einstein

We can use this insanity principle to our advantage with pure functions.

Assigning values to variables during an imperative function's execution may result in the modification of a variable in the environment in which it has run. If we run the same imperative function again, using the same input, the result may differ.

Given the results of an imperative function and given the same input, different results may be returned each time it is run. Is that not insanity?

Pure functions:

  • Treat functions as first-class citizens
  • Always return the same result given the same input(s)
  • Have no side effects in the environment in which they run
  • Do not allow an external state to affect their results
  • Do not allow variable values to change over time

Two characteristics of a pure function include referential transparency and idempotence:

  • Referential transparency: This is where a function call can be replaced with its corresponding value without changing the program's behavior
  • Idempotence: This is where a function call can be called repeatedly and produce the same result each time

Referentially transparent programs are more easily optimized. Let's see whether we can perform optimizations using a caching technique and Go's concurrency features.