Characteristics of FP
Let's start by looking at the requirements for a pure FP language. A pure FP language must include support for things like:
- First-class functions
- Tail-call optimization (TCO)
- High-order functions
- Pure functions
- Immutable Data
In order to accomplish pure FP, a language must treat functions as it does any other variable type. How can an immutable language have variables that vary? The way we accomplish this in an FP way is by creating new variables, rather than modifying existing ones. We will see how to accomplish this later in the chapter, when we look at the Map function.
Go is a multidimensional language that supports imperative, object-oriented, and FP styles. We could write a purely imperative or functional program in Go. It is our choice of programming style that dictates this. This is one of the great things about Go and FP. It's not an all or nothing issue. We can migrate our code toward FP when and where it makes sense to do so.
Go requires tail-call optimization (TCO) to handle production performance requirements. Each time a recursive function calls itself, a new block is added to the stack frame; we soon feel the sluggish effects of this Go compiler omission. We will see how to mitigate this issue when we implement the Reduce function.
The last requirement is support for high-order functions (HOF). High-order functions take functions as arguments and/or return functions as their result. HOFs allow us to chain our functions together in a readable manner with less code.
HOFs are arguably the focal point of any FP language, and after a quick look at FP characteristics, we'll study how we can exploit them in Go:
These are not all characteristics of a pure FP, just some of the more significant ones. Probably the most important one is support for first class functions.
The preceding table introduces a lot of concepts that we'll cover in greater detail later in our book. Feel free to skip ahead if your curiosity is too great; Otherwise, just go with the flow and we'll eventually get to it.
In the Supported in Go? column in the preceding table:
- Yes!: Indicates that the FP characteristic exists in Go.
- Yes: Indicates that the characteristic or requirement can be achieved with some effort in Go.
- No: Indicates that this FP characteristic or requirement is missing and is difficult or not possible to achieve without a major upgrade to the Go compiler, or without using another technology in tandem with Go.