Runtime evaluation: Difference between revisions

expand CL example into the kind of discussion I intended all examples to have
(expand CL example into the kind of discussion I intended all examples to have)
Line 7:
=={{header|Common Lisp}}==
 
<lang lisp>(eval '(+ 4 5)) ; Evaluate the program (+ 4 5)</lang>
===Using a list to represent code===
 
<lang lisp>(eval '(+ 4 5)) ; Evaluate the program (+ 4 5)</lang>
returns 9.
 
In Common Lisp, programs are represented as trees (s-expressions). Therefore, it is easily possible to construct a program which includes externally specified values, particularly using backquote template syntax:
 
<lang lisp>(defun add-four-complicated (a-number)
(eval `(+ 4 ',a-number)))</lang>
 
Or you can construct a function and then call it. (If the function is used more than once, it would be good to use <code>[http://www.lispworks.com/documentation/HyperSpec/Body/f_cmp.htm compile]</code> instead of <code>eval</code>, which compiles the code before returning the function. <code>eval</code> is permitted to compile as well, but <code>compile</code> requires it.)
 
<lang lisp>(defun add-four-by-function (a-number)
(funcall (eval '(lambda (n) (+ 4 n)))) a-number)</lang>
 
If your program came from a file or user input, then you have it as a string, and [http://www.lispworks.com/documentation/HyperSpec/Body/f_rd_rd.htm read] or read-from-string will convert it to s-expression form:
<lang lisp>(eval (read-from-string "(+ 4 5)")) ; Evaluate the program (+ 4 5)</lang>
 
Common Lisp has lexical scope, but <code>eval</code> always evaluates “in the null lexical environment”. In particular, it does not inherit the lexical environment from the enclosing code. (Note that <code>eval</code> is an ordinary function and as such does not have access to that environment anyway.)
 
<lang lisp>(let ((x 1))
(eval `(+ x 1))) ; this will fail unless x is a special variable or has a dynamic binding</lang>
 
===Using a String to represent code===
<lang lisp>(eval (read-from-string "(+ 4 5)")) ; Evaluate the program (+ 4 5)</lang>
 
=={{header|Groovy}}==