Now that you’ve worked your way through this book, here is one final reward: A story about the technologies behind the entire Lisp family of programming languages, set in the not-too-distant future . . .
Functional programming is a mathematical approach to programming that was pioneered by the creators of Lisp. Functional programming places certain restrictions on the programmer, but it can lead to very elegant code. When using functional programming, every variable that is used by a given function must be one of the following:
A parameter passed into that function
A local variable created within that function
A constant
Also, functional programming doesn’t allow a function to have side effects. This means a function can’t write to the disk, print messages on the screen, or do anything other than return a result. The goal is to write most of a program using “functional code,” while retaining a teensy bit of code that does any dirty, nonfunctional stuff that is still needed.
Writing code in a functional style guarantees that a function does only one thing (returns a value) and is dependent on one only thing (the parameters passed to it). This makes it very easy to debug. No matter how many times you run a function, as long as you’re passing it the same data, you will always get the same result.
If you enter this code into the Lisp REPL and execute (ask-and-respond)
, you will be asked for your name, and then greeted by your name but with all duplicate letters removed. All the hard work in this function is handled by unique-letters
, which is written in a functional style . The dirty work of interacting with the user, which can’t be written in a purely functional way, is handled by ask-and-respond
.
The main weakness of functional programming is that some side effects are almost always necessary for a program to actually do something. This means you can’t write a useful program that has the entirety of its code written in the functional style. At least a small amount of code will be nonfunctional.
Functional programming is discussed in Chapter 14.
3.144.15.154