7 Functional programming with comprehensions

 

Programmers are always trying to do more with less code, while simultaneously making that code more reliable and easier to debug. And indeed, computer scientists have developed a number of techniques, each meant to bring us closer to that goal of short, reliable, maintainable, powerful code.

One set of techniques is known as functional programming. It aims to make programs more reliable by keeping functions short and data immutable. I think most developers would agree that short functions are a good idea, in no small part because they’re easier to understand, test, and maintain.

But how can you enforce the writing of short functions? Immutable data. If you can’t modify data from within a function, then the function will (in my experience) end up being shorter, with fewer potential paths to be tested. Functional programs thus end up having many short functions—​in contrast with nonfunctional programs, which often have a smaller number of very long functions. Functional programming also assumes that functions can be passed as arguments to other functions, something that we’ve already seen to be the case in Python.

7.1 Exercise 28 ■ Join numbers

7.1.1 Working it out

7.1.2 Beyond the exercise

7.2 Exercise 29 ■ Add numbers

7.2.1 Working it out

7.2.2 Solution

7.2.3 Beyond the exercise

7.3 Exercise 30 ■ Flatten a list

7.3.1 Working it out

7.3.2 Beyond the exercise

7.4 Exercise 31 ■ Pig Latin translation of a file

7.4.1 Working it out

7.4.2 Solution

7.4.3 Beyond the exercise

7.5 Exercise 32 ■ Flip a dict

7.5.1 Working it out

7.5.2 Solution

7.5.3 Beyond the exercise

7.6 Exercise 33 ■ Transform values

7.6.1 Working it out

7.6.2 Solution

7.6.3 Beyond the exercise

7.7 Exercise 34 ■ (Almost) supervocalic words

7.7.1 Working it out

7.7.2 Solution

7.7.3 Beyond the exercise