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.

Exercise 28 Join numbers

 
 
 
 

Working it out

 
 
 

Solution

 
 

Screencast solution

 
 
 
 

Beyond the exercise

 
 
 
 

Exercise 29 Add numbers

 
 

Working it out

 
 
 
 

Solution

 
 
 

Screencast solution

 
 
 

Beyond the exercise

 

Exercise 30 Flatten a list

 
 

Working it out

 
 
 
 

Solution

 
 

Screencast solution

 
 
 

Beyond the exercise

 
 
 

Exercise 31 Pig Latin translation of a file

 
 
 
 

Working it out

 
 

Solution

 
 

Screencast solution

 
 
 
 

Beyond the exercise

 
 

Exercise 32 Flip a dict

 
 
 

Working it out

 
 
 

Solution

 
 

Screencast solution

 

Beyond the exercise

 
 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage