Search code examples
functionlispcommon-lispclisp

How do I execute a Lisp program which has been stored in a variable?


I have this code:

(setf prg '(+ 1 n)) ; define a very simple program
(print prg) ; print the program

I need to add more code so that when the above code is executed, it should set n to 1 and execute the program stored in variable prg.


Solution

  • I think you want to do this:

    (setf prg (lambda (n) + 1 n)) ; define a very simple program
    (print (funcall prg 1))       ; print the program
    

    In your example: (+ 1 n) is not a valid Common Lisp program.

    EDIT: If you wanted to play with variables binding, you could also declare a variable:

    (setf prg '(+ 1 n)) ; define a Common Lisp expression
    (defparameter n 1)  ; bind a variable to the value 1
    (print (eval prg))  ; evaluate the Common Lisp expression
    > 2