Next: , Previous: , Up: Welcome to Lisp   [Contents][Index]


16.4.12 Functional Programming

Functional programming means writing programs that work by returning values instead of by modifying things. It is the dominant paradigm in Lisp. Most build-in Lisp functions are meant to be called for the values they return, not for side-effects.

The function remove takes an object and a list and returns a new list containing everything but that object.

> (setf lst ’(c a r a t))
(C A R A T)
> (remove ’a lst)
(C R T)

The origin list is untouched afterwards:

> lst
(C A R A T)

So what if you really do want to remove something from a list? In Lisp, you generally do such things by passing the list as an argument to some function, and using setf with the return value. To remove all the ‘a’ s from a list, we say:

(setf x (remove ’a x))

Functional programming means avoiding setf and things like it.

One of the most important advantages of functional programming is that it allows interactive testing. In purely functional code, you can test each function as you write it. If it returns the values you expect, you can be condfident that it is correct. You have instant turnaround when you make changes anywhere in a program. And this instant turnaround enables a whole new style of programming.