3 Functional Programming
This chapter covers:
- Using the full gambit of input variables, local values, and output values
- Making Terraform more expressive with functions and for expressions
- Incorporating two new providers: Random and Archive
- Templating with templatefile()
- Scaling resources with count
Functional programming is a declarative programming paradigm that allows you to do many things in a single line of code. By composing small modular functions, you are able to tell a computer what you want it to do, instead of how to do it. Functional programming is called functional programming because, as the name implies, programs consist almost entirely of functions. The core principles of functional programming are:
- Pure Functions – functions return the same value for the same arguments, never having any side effects.
- First-class and Higher-order functions – functions are treated like any other variable, and can be saved, passed around, and used to compose higher-order functions.
- Immutability – data is never directly modified. Instead, new data structures are created each time data would change.
To give you an idea the difference between procedural and functional programming, here is procedural JavaScript code that multiples all even numbers in an array by 10 and adds the results together:
const numList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] let result = 0; for (let i = 0; i < numList.length; i++) { if (numList[i] % 2 === 0) { result += (numList[i] * 10) } }