Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Learning Functional Programming in Go

You're reading from   Learning Functional Programming in Go Change the way you approach your applications using functional programming in Go

Arrow left icon
Product type Paperback
Published in Nov 2017
Publisher Packt
ISBN-13 9781787281394
Length 670 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Lex Sheehan Lex Sheehan
Author Profile Icon Lex Sheehan
Lex Sheehan
Arrow right icon
View More author details
Toc

Table of Contents (13) Chapters Close

Preface 1. Pure Functional Programming in Go 2. Manipulating Collections FREE CHAPTER 3. Using High-Order Functions 4. SOLID Design in Go 5. Adding Functionality with Decoration 6. Applying FP at the Architectural Level 7. Functional Parameters 8. Increasing Performance Using Pipelining 9. Functors, Monoids, and Generics 10. Monads, Type Classes, and Generics 11. Category Theory That Applies 12. Miscellaneous Information and How-Tos

Imperative versus declarative programming

Let's look at why the functional style of programming helps us be more productive than the imperative alternative.

"We are not makers of history. We are made by history."
- Martin Luther King, Jr.

Nearly all computer hardware is designed to execute machine code, which is native to the computer, written in the imperative style. The program state is defined by the contents of memory, and the statements are instructions in the machine language where each statement advances the state of computation forward, toward a final outcome. Imperative programs change their state over time, step by step. High-level imperative languages, such as C and Go, use variables and more complex statements, but they still follow the same paradigm. Since the basic ideas in imperative programming are both conceptually similar to low-level code that operates directly on computer hardware, most computer languages--such as Go, also known as C of the 21st century--are largely imperative.

Imperative programming is a programming paradigm that uses statements that change a program's state. It focuses on the step-by-step mechanics of how a program operates.

The term is often used in contrast to declarative programming. In declarative programming, we declare what we want the results to be. We describe what we want, not detailed instructions of how to get it.

Here's a typical, imperative way to find Blazer in a slice of cars:

var found bool 
carToLookFor := "Blazer"
cars := []string{"Accord", "IS250", "Blazer" }
for _, car := range cars {
if car == carToLookFor {
found = true; // set flag
}
}
fmt.Printf("Found? %v", found)

Here's a functional way of accomplishing the same task:

cars := []string{"Accord", "IS250", "Blazer" }
fmt.Printf("Found? %v", cars.contains("Blazer"))

That's nine lines of imperative code, compared to two lines in the functional programming (FP) style.

Functional constructs often express our intent more clearly than for loops in such cases and are especially useful when we want to filter, transform, or aggregate the elements in a dataset.

In the imperative example, we must code the how. We must:

  • Declare a Boolean flag
  • Declare and set a variable value
  • Create a looping structure
  • Compare each iterated value
  • Set the flag

In the functional example, we declare what we want to do. We are able to focus on what we want to accomplish, rather than bloating our code with the mechanics of looping structures, setting variable values, and so on.

In FP, iteration is implemented by the library function contains(). Leveraging library functions means that we code less and allow library developers to focus on highly efficient implementations, which have been typically vetted and performance enhanced by seasoned professionals. We don't have to write, debug, or test such high-quality code for repetitive logic.

Now, let's look at how we could look for Blazer using the object-oriented programming paradigm:

type Car struct {
Model string
}
accord := &Car{"Accord"}; is250 := &Car{"IS250"}; blazer := &Car{"Blazer"}
cars := []*Car{is250, accord, blazer}
var found bool
carToLookFor := is250
for _, car := range cars {
if car == carToLookFor {
found = true;
}
}
fmt.Printf("Found? %v", found)

First, we declare our object types:

type Car struct {
Model string
}
type Cars []Car

Next, we add our methods:

func (cars *Cars) Add(car Car) {
myCars = append(myCars, car)
}

func (cars *Cars) Find(model string) (*Car, error) {
for _, car := range *cars {
if car.Model == model {
return &car, nil
}
}
return nil, errors.New("car not found")
}

Here, we declare a global variable, namely myCars, where we will persist the state, that is, the list of cars that we will build:

var myCars Cars

Add three cars to the list. The Car object encapsulates the data for each object, and the cars object encapsulates our list of cars:

func main() {
myCars.Add(Car{"IS250"})
myCars.Add(Car{"Blazer"})
myCars.Add(Car{"Highlander"})

Look for Highlander and print the results:

    car, err := myCars.Find("Highlander")
if err != nil {
fmt.Printf("ERROR: %v", car)
} else {
fmt.Printf("Found %v", car)
}
}

We are using car objects, but we are essentially doing the same operations as we were in the simple imperative code example. We do have objects that have state and to which we could add methods, but the underlying mechanisms are the same. We assign a state to object properties, modify the internal state by making method calls, and advance the state of execution until we arrive at the desired outcome. That's imperative programming.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime