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)
  }
}

3.1    Fun with Mad Libs

 
 

3.1.1   Input Variables

 
 
 
 

3.1.2   Assigning Values with a Variable Definition File

 
 
 

3.1.3   Validating Variables

 
 
 
 

3.1.4   Shuffling Lists

 
 
 
 

3.1.5   Functions

 
 
 

3.1.6   Output Values

 

3.1.7   Templates

 
 

3.1.8   Printing Output

 
 
 

3.2    Generating Many Mad Libs

 

3.2.1   For Expressions

 
 
 

3.2.2   Local Values

 
 

3.2.3   Implicit Dependencies

 
 
 
 

3.2.4   Count Parameter

 
 

3.2.5   Conditional Expressions

 
 

3.2.6   More Templates

 
 
 

3.2.7   Local File

 
 

3.2.8   Zipping Files

 
 

3.2.9   Applying Changes

 
 
 
 

3.3    Fireside Chat

 
 
 

3.4    Summary

 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest