Functional Programming in Go - Dylan Meeus - E-Book

Functional Programming in Go E-Book

Dylan Meeus

0,0
28,79 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

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.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 330

Veröffentlichungsjahr: 2023

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Functional Programming in Go

Apply functional techniques in Golang to improve the testability, readability, and security of your code

Dylan Meeus

BIRMINGHAM—MUMBAI

Functional Programming in Go

Copyright © 2023 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Manager: Gebin George

Publishing Product Manager: Pooja Yadav

Senior Editor: Ruvika Rao

Technical Editor: Maran Fernandes

Copy Editor: Safis Editing

Project Coordinator: Deeksha Thakkar

Proofreader: Safis Editing

Indexer: Pratik Shirodkar

Production Designer: Joshua Misquitta

DevRel Marketing Coordinator: Sonia Chauhan

First published: March 2023

Production reference: 1270223

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-80181-116-3

www.packtpub.com

To my grandmother, Yvonne Hombroeckx, and to the memory of my grandfather, Remi Vandeput, for their unconditional love and support, and for being my role models in life. To my wife, Ana, for always believing in me and joining me as we explore the world together.

– Dylan Meeus

Contributors

About the author

Dylan Meeus is a software engineer, with over a decade of experience building software using various functional and object-oriented programming languages. He has used Go to develop systems in a variety of domains, from healthcare to machine learning and digital signal processing software. He developed a passion for functional programming when learning Haskell and applied this knowledge to traditionally non-functional languages, such as Java. Over the past several years, Dylan has been a speaker at various Go and Java-oriented conferences such as GopherCon and Devoxx.

First and foremost, I would like to thank my wife, Ana, for her words of encouragement and support throughout the process of writing this book, as well as our dog, Bucky, for letting me know when it was time to take a break and go for a walk. I also want to thank Tom and the team at Packt, whose technical advice and reviews helped shape this book.

About the reviewer

Tom Deboosere is a software developer with over 10 years of experience in the healthcare sector. He started out as a C++ developer, pivoting to Java and then Go.

He currently works for nexuzhealth as a full-time technical domain lead, working on software used by 35+ care facilities, with over a million users.

He also likes to cook, play board games, and take long walks on the beach...

…as long as the beach is in virtual reality.

Table of Contents

Preface

Part 1: Functional Programming Paradigm Essentials

1

Introducing Functional Programming

What is functional programming?

Introducing first-class functions

What are pure functions?

Say what you want, not how you want it    

A brief history of functional programming

Modern functional programming

The Go programming paradigm

Why functional programming?

Why not functional programming in Go?

Comparing FP and OOP

Summary

2

Treating Functions as First-Class Citizens

Technical requirements

Benefits of first-class functions

Defining types for functions

Type aliases for primitives

Type aliases for functions

Using functions as objects

Passing functions to functions

In-line function definitions

Anonymous functions

Returning functions from functions

Functions in var

Functions inside data structures

Functions inside structs

Example 1 – map dispatcher

Creating a simple calculator

Example 2 – mocking functions for testing

Summary

3

Higher-Order Functions

Technical requirements

An introduction to higher-order functions

Closures and variable scoping

Variable scoping in Go

Capturing variable context in functions (closures)

Partial application

Function currying, or how to reduce n-ary functions to unary functions

Example: function currying

Example: server constructor

Summary

4

Writing Testable Code with Pure Functions

Technical requirements

What is purity?

Demonstrating pure versus impure function calls

Referential transparency

Idempotence

Statelessness

Side effects

Why does purity improve our code?

Increases the testability of our code

Increases the confidence in our code

Improved confidence in function names and signatures

Safer concurrency

When not to write pure functions

Input/output operations

Non-determinism can be desired

When we really have to panic!

How do we create pure functions?

Avoid global state

Separate pure and impure functionality

Example 1 – hotdog shop

Bad hotdog shop

Better hotdog shop

Summary

5

Immutability

Technical requirements

What is immutability?

Immutability at the data layer

How to write immutable code in Go

Writing immutable code for collection data types

Measuring performance in mutable and immutable code

Benchmarking functions

Understanding stacks, heaps, and garbage collection

When to write mutable functions

What are functors and monads?

What’s a functor?

From functor to monad

Summary

Part 2: Using Functional Programming Techniques

6

Three Common Categories of Functions

Technical requirements

Predicate-based functions

Implementing a Filter function

Any or all

Implementing DropWhile and TakeWhile

Map/transformation functions

Transformations while maintaining the data type

Data reducing functions

Example – working with airport data

Summary

7

Recursion

Technical requirements

What is recursion?

Why do functional languages favor recursion?

When to use recursive functions

Iterating over trees

Recursion and functions as first-class citizens

Limits of recursive functions

Measuring the performance of recursive versus iterative solutions

Space limitation of recursive functions

Tail recursion as a solution to stack limitations

Summary

8

Readable Function Composition with Fluent Programming

Technical requirements

Chaining functions through dot notation

Chaining methods for object creation (builder pattern)

Dot notation to chain functions on slices

Infinite data structures and lazy evaluation

Continuation-passing style programming

CPS and goroutines

When to use CPS?

Summary

Part 3: Design Patterns and Functional Programming Libraries

9

Functional Design Patterns

Technical requirements

Classical design patterns in a functional paradigm

The strategy pattern

The decorator pattern

The Hollywood principle

Functional design patterns

Summary

10

Concurrency and Functional Programming

Technical requirements

Functional programming and concurrency

Concurrency, parallelism, and distributed computing

Functional programming and concurrency

Creating concurrent functions

Concurrent filter implementation

Concurrent Map and FMap implementation

The pipeline pattern

Summary

11

Functional Programming Libraries

Technical requirements

Is the library alive – and do the examples still match it?

Legal requirements

Pre-generics libraries for creating common FP functions

Code generation libraries for pre-generics Go

Post-generics functional programming libraries

Pie with generics

Lodash, for Go

Mo, for go

Summary

Index

Other Books You May Enjoy

Preface

Go is a multi-paradigm programming language. This means that both the object-oriented paradigm and the functional paradigm are entirely valid approaches to problem solving. In this book, we will explore the applications of functional programming techniques in Go. But rather than being purely focused on the functional aspect, we will embrace Go for what it is – multi-paradigm. This means that we highlight the difference between the functional and object-oriented ways of problem solving.

To write Go code that is more testable, readable, and reliable, we will look at functional-first approaches such as functions as first-class citizens, function purity, currying, and more. We will look not only at how to write functional code, but we will also explore the performance implications and limitations of Go.

The goal of this book is to get the reader accustomed to functional programming as a valid paradigm that can improve your code, no matter whether you’re working on a greenfield project or a project already entrenched in the OO paradigm.

For readers unfamiliar with the newly introduced generics in Go, this book also serves as an example of what’s possible now that generics are part of the standard library. Finally, we will also look at libraries that can be leveraged to write functional code for both pre-generic and post-generic versions of Go.

Who this book is for

If you are a Go engineer with a background in traditionally object-oriented languages such as Java or C++ who wants to broaden your knowledge of functional programming, this book is for you. The book aims to teach you how concepts from functional programming can improve your existing Go code, as well as when to choose the functional approach. At each step, we highlight the trade-offs between the functional and object-oriented approaches to see how they compare.

What this book covers

In Chapter 1, Introducing Functional Programming, we are going to take a bird’s eye view of the what and why behind functional programming. To start, we will take a brief look at the history and contemporary state of functional programming methodologies. Then we will take a look at how functional programming compares to the more traditional object-oriented programming.

InChapter 2, Treating Functions as First-Class Citizens, we are going to cover exactly why functions are powerful in languages that treat them as first-class citizens. Go has functions as first-class citizens out of the box, meaning we get this functionality. We are going to see how this allows us to create function-centered constructs that improve the readability and testability of our code.

InChapter 3, Higher-Order Functions, we are going to explore the concept of function composition through higher-order functions. There are a variety of new concepts that are introduced here, such as closures, partial application, and function currying. We will take a look at some practical examples and real-world use cases for these.

InChapter 4, Write Testable Code with Pure Functions, we will take a look at what it means for a language, and a function, to be considered pure. We will take a look at some of the tradeoffs between function purity and impurity, and explore how pure functions help us write testable code.

InChapter 5, Immutability, we cover what exactly it means to be immutable, and how the Go language can help preserve immutability at the struct level. To understand how this works, we will look at how Go handles pointers and references to objects, what the performance implications are, and how to decide between the pointer-reference trade-offs. We will also dive into the implications for garbage collection, unit testing, and pure functional programming.

InChapter 6, Three Common Categories of Functions, we are going to look at some practical implementations of functions that leverage the concepts of functional programming covered up to now. We will build Filter functions, Map functions and Reducers.

InChapter 7, Recursion, we are going to talk about recursion. This is a topic that all programmers encounter sooner or later, as it’s not exclusive to the functional paradigm. Any language in which you can express function calls also allows you to express functions that are recursive in nature. But in functional languages, these take center stage. We will look at the implications for this in Go.

InChapter 8, Readable Function Composition with Fluent Programming, we are going to look at different methods for chaining functions in functional programming. The end goal here is to write code that is easier to read and creates less visual clutter. We will look at three ways for achieving this. First, we will take a look at how we can use type aliases to attach methods to container types, allowing us to create chained functions with the familiar dot notation. Next, we will look at continuation-passing style programming and consider the trade-offs of each approach.

InChapter 9, Functional Design Patterns, we will move to a higher level of abstraction. Rather than talking about individual functions and operations, we will look at design patterns. While we will not extensively explain each design pattern, we will take a look at how the object-oriented pattern translates to the functional world.

InChapter 10, Concurrency and Functional Programming, we consider how concurrency is all around us, both in the real world as well as the virtual one. In this chapter we will start by looking at concurrency, parallelism, and distributed computation. Next, we will focus on how the concurrency mechanisms in Go can help us write functional code.

InChapter 11, Functional Programming Libraries, we will explore several libraries that can help us build programs in the functional paradigm. We will look both at pre-generic libraries and post-generic libraries.

To get the most out of this book

Prior to picking up this book, the reader should be familiar with Go and generics. The basic concepts of the programming language (control flow, structs, and imports), how to build and run applications, and how to import open source libraries from GitHub should also be understood by the reader.

Software/hardware covered in the book

Operating system requirements

Go (pre- and post-generics)

Windows, macOS, or Linux

Having Go 1.18 or later installed is a prerequisite for the majority of this book. Certain chapters will also work on Go version’s prior to 1.18, this will be called out per chapter. Most of the code will also work in the Go playground athttps://go.dev/play/.

If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

Some chapters will have snippets in Haskell and Java for illustrative purposes of (pure) functional and object-oriented counterparts to Go.

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Functional-Programming-in-Go. If there’s an update to the code, it will be updated in the GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots and diagrams used in this book. You can download it here: https://packt.link/5tPDg.

Conventions used

There are a number of text conventions used throughout this book.

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “When calling the rollDice function, the output is not consistent. If it were consistently outputting the same number, it would be a pretty bad randomization function.”

A block of code is set as follows:

func rollDice() int { return rand.Intn(6) }

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

go test -bench=.

Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: “In this main function, we are first defining a deferred function that runs at the end of main function, just before function exit.”

Tips or important notes

Appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Share your thoughts

Once you’ve read Functional Programming in Golang, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

Download a free PDF copy of this book

Thanks for purchasing this book!

Do you like to read on the go but are unable to carry your print books everywhere?

Is your eBook purchase not compatible with the device of your choice?

Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.

The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily

Follow these simple steps to get the benefits:

Scan the QR code or visit the link below

https://packt.link/free-ebook/9781801811163

Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directly

Part 1: Functional Programming Paradigm Essentials

In this part, we will take a look at what the functional programming paradigm entails. We’ll look at how it compares to the traditional object-oriented approach, and learn some language design differences between programming languages in each paradigm. We’ll also discuss what it means for Go to be a multi-paradigm language and see how this benefits our use case. Finally, we’ll look at some key ideas in functional programming, which we can leverage to write more readable, maintainable, and testable code.

This part has the following chapters:

Chapter 1, Introducing Functional ProgrammingChapter 2, Treating Functions as First-Class CitizensChapter 3, Higher-Order FunctionsChapter 4, Write Testable Code with Pure FunctionsChapter 5, Immutability