The Symmetry Between Code and Data in Lisp

You have seen that Lisp has very elegant and symmetrical facilities for translating raw string data from the outside world and converting it to and from Lisp syntax expressions. But Lisp has an even deeper symmetry. It can treat program code and data interchangeably. A programming language that uses the same data structures to store data and program code is called homoiconic.

You saw an example of homoiconicity in Chapter 3, when we discussed code mode and data mode. In that example, we used the quote to change between the two modes:

> '(+ 1 2) ;data mode
(+ 1 2)
> (+ 1 2) ;code mode
3

In the previous chapter, we took this concept one step further by using a quasiquote when defining the describe-path function.

But the quoting and quasiquoting facilities in Lisp are somewhat limited in their abilities. What if we generate a piece of Lisp code from scratch somehow and wish to execute it as if it were a piece of code? For example, let’s store a raw chunk of code inside a variable:

> (defparameter *foo* '(+ 1 2))
*FOO*

How could we execute the code that’s in the *foo* variable? We need an even more powerful command to make this possible. This is the eval command:

> (eval *foo*)
3

Because the eval command is so powerful and yet so simple, it is extremely enticing to beginning Lispers. You want to write a program with self-modifying code? Then eval will be your best friend. In fact, this is probably the main reason why the artificial intelligence (AI) freaks back in the day loved Lisp so much. Go ahead and try writing some programs that use the eval command. You’ll find that it’s a lot of fun.

However, an experienced Lisper will only rarely use eval. Until you have a few thousand lines of Lisp code under your belt, you really won’t know when it is appropriate to use this extremely powerful command. Often, a beginning Lisper will use the eval command instead of defining a Lisp macro. We will discuss macros in Chapter 16.

The bottom line is that the symmetry of data and code in Lisp pretty much makes Lisp the poster child of homoiconicity. Quoting, quasiquoting, the eval command, and macros allow you to take advantage of this property in your code.

Warning

Inexperienced use of eval can pose a security risk. See The Dangers of read and eval in The Dangers of read and eval for more information.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.132.99