Homoiconicity - Examples - Homoiconicity in Lisp

Homoiconicity in Lisp

Lisp uses S-expressions as an external representation for data and code. S-expressions can be read with the primitive Lisp function READ. READ returns Lisp data: lists, symbols, numbers, strings. The primitive Lisp function EVAL uses Lisp code represented as Lisp data, computes side-effects and returns a result. The result will be printed by the primitive function PRINT, which creates an external S-expression from Lisp data.

Lisp data, a list using different data types: (sub)lists, symbols, strings and integer numbers.

((:name "john" :age 20) (:name "mary" :age 18) (:name "alice" :age 22))

Lisp code. The example uses lists, symbols and numbers.

(* (sin 1.1) (cos 2.03)) ; in infix: sin(1.1)*cos(2.03)

Create above expression with the primitive Lisp function LIST and set the variable EXPRESSION to the result

(setf expression (list '* (list 'sin 1.1) (list 'cos 2.03)) ) -> (* (SIN 1.1) (COS 2.03)) ; Lisp returns and prints the result (third expression) ; the third element of the expression -> (COS 2.03)

Change the COS term to SIN

(setf (first (third expression)) 'SIN) ; The expression is now (* (SIN 1.1) (SIN 2.03)).

Evaluate the expression

(eval expression) -> 0.7988834

Print the expression to a string

(princ-to-string expression) -> "(* (SIN 1.1) (SIN 2.03))"

Read the expression from a string

(read-from-string "(* (SIN 1.1) (SIN 2.03))") -> (* (SIN 1.1) (SIN 2.03)) ; returns a list of lists, numbers and symbols

Read more about this topic:  Homoiconicity, Examples

Famous quotes containing the word lisp:

    Taught me my alphabet to say,
    To lisp my very earliest word,
    Edgar Allan Poe (1809–1849)