Book Image

Hands-On Functional Programming with TypeScript

By : Remo H. Jansen
Book Image

Hands-On Functional Programming with TypeScript

By: Remo H. Jansen

Overview of this book

Functional programming is a powerful programming paradigm that can help you to write better code. However, learning functional programming can be complicated, and the existing literature is often too complex for beginners. This book is an approachable introduction to functional programming and reactive programming with TypeScript for readers without previous experience in functional programming with JavaScript, TypeScript , or any other programming language. The book will help you understand the pros, cons, and core principles of functional programming in TypeScript. It will explain higher order functions, referential transparency, functional composition, and monads with the help of effective code examples. Using TypeScript as a functional programming language, you’ll also be able to brush up on your knowledge of applying functional programming techniques, including currying, laziness, and immutability, to real-world scenarios. By the end of this book, you will be confident when it comes to using core functional and reactive programming techniques to help you build effective applications with TypeScript.
Table of Contents (14 chapters)
5
The Runtime – Closures and Prototypes

Declarative versus imperative programming

The advocates of the FP paradigm often use declarative programming as one of its main benefits. Declarative programming is not necessarily exclusive to functional programming, but FP certainly encourages or facilitates this programming style. Before we take a look at some examples, we are going to define declarative programming and imperative programming:

  • Imperative programming is a programming paradigm that uses statements that change a program's state. In much the same way that the imperative mood in natural languages expresses commands, an imperative program consists of commands for the computer to perform. Imperative programming focuses on describing how a program operates.
  • Declarative programming is a programming paradigm that expresses the logic of a computation without describing its control flow. Many languages that apply this style attempt to minimize or eliminate side-effects by describing what the program must accomplish in terms of the problem domain, rather than describing how to accomplish it as a sequence of steps.

The following example calculates the average result of an exam given a collection of objects that contains an ID and a result for a list of students. This example uses an imperative programming style because, as we can see, it uses control flow statements (for). The example is also clearly imperative because it mutates a state. The total variable is declared using the let keyword because it is mutated as many times as results are contained in the results array:

interface Result {
id: number;
result:number;
}

const results: Result[] = [
{ id: 1, result: 64 },
{ id: 2, result: 87 },
{ id: 3, result: 89 }
];

function avg(arr: Result[]) {
let total = 0;
for (var i = 0; i < arr.length; i++) {
total += arr[i].result;
}
return total / arr.length;
}

const resultsAvg = avg(results);
console.log(resultsAvg);

On the other hand, the following example is declarative because there are no control flow statements and there are no state mutations:

interface Result {
id: number;
result:number;
}

const results: Result[] = [
{ id: 1, result: 64 },
{ id: 2, result: 87 },
{ id: 3, result: 89 }
];

const add = (a: number, b: number) => a + b;
const division = (a: number, b: number) => a / b;

const avg = (arr: Result[]) =>
division(arr.map(a => a.result).reduce(add, 0), arr.length)

const resultsAvg = avg(results);
console.log(resultsAvg);

While the previous example is declarative, it is not as declarative as it could be. The following example takes the declarative style one step further so we can get an idea of how a piece of declarative code may appear. Don't worry if you don't understand everything in this example right now. We will be able to understand it once we learn more about functional programming techniques later in this book. Note how the program is now defined as a set of very small functions that don't mutate the state and that also don't use control flow statements. These functions are reusable because they are independent of the problem that we are trying to solve. For example, the avg function can calculate an average, but it doesn't need to be an average of results:

const add = (a: number, b: number) => a + b;
const addMany = (...args: number[]) => args.reduce(add, 0);
const div = (a: number, b: number) => a / b;
const mapProp = <T>(k: keyof T, arr: T[]) => arr.map(a => a[k]);
const avg = (arr: number[]) => div(addMany(...arr), arr.length);

interface Result {
id: number;
result:number;
}

const results: Result[] = [
{ id: 1, result: 64 },
{ id: 2, result: 87 },
{ id: 3, result: 89 }
];

const resultsAvg = avg(mapProp("result", results));
console.log(resultsAvg);

The actual code that is specific to the problem that we are trying to solve is very small:

const resultsAvg = avg(mapProp("result", results));

This code is not reusable, but the add, addMany, div, mapProp, and avg functions are reusable. This demonstrates how declarative programming can lead to more reusable code than imperative programming.