Search code examples
emacsmacroslispevalhomoiconicity

why is it useful to treat code as data in lisp


I learn emacs lisp now and I wonder why it maybe useful to treat code as data. What a benefits of this approach. I saw one explanation as this is alternative to traditional Von Neumann architecture where exists clear separattion between data and code. I'd like to understand a meaning for this decision, get the idea.

Thanks in advance, Nick.


Solution

  • You can write code that will write code for you. This can be done in two ways:

    • First, your program can create new code as a list and pass it to the eval function, which will evaluate the new code at runtime (however, eval is something you should not abuse -- actually, it should be used seldomly, when you really need it). You could theoretically do this in languages that do not have the homoiconicity property, but it would be a lot harder. For example, in Scheme you may do this
    (define form '(x 10))
    (set! form (append 'define form)
    (eval form (interaction-environment)
    

    and the value of x will be 10 after that. This could be used, for example, in Genetic Programming

    • You may also define macros. A macro is a little function that reads something that looks like a function call, but is translated (expanded) into something else before the program starts evaluating forms (that is, before it is run). For example, in many Lisps or is a macro. This code,
    (or a b c)
    

    is translated into

    (let ((tmp1 a))
      (if tmp1
          tmp1
          (let ((tmp2 b))
            (if tmp2
                tmp2
                (let ((tmp3 c))
                  (if tmp3
                      tmp3
                      #f))))))
    

    You could implement or as a function, but then the function would have to evaluate all its arguments before returning. Since or is a macro, it will not necessarily evaluate all arguments.

    You can read more about macros in Wikipedia and in this cool book [ beside several other places on the net, like here, here and here for example ]. And you can read about eval in Wikipedia and in this great book.

    You can also read Paul Graham's On Lisp (the book is completely free), which teaches basic Common Lisp in a somewhat fast pace and then gets into all kinds of programming techniques with macros, and later you can try Let Over Lambda (only some chapters are free).

    About eval it may be interestig to read this question and its answers.