For a code like this:
(+ (* 8 8) (* 4 4))
You will have the following tree:
I recommend to read about "Abstract Syntax Tree" and Lisp S-Expressions.
Question
I'm learning Clojure at the moment. I keep reading the following statement:
"Lisp programs are trees of expressions"
I'm not quite sure I understand it. Could someone explain it to me?
Thanks!
La solution
For a code like this:
(+ (* 8 8) (* 4 4))
You will have the following tree:
I recommend to read about "Abstract Syntax Tree" and Lisp S-Expressions.
Autres conseils
We think of a Lisp program as data/S-expressions/trees because of the existence of the reader, the first part of Lisp your program sees. The reader
This data structure is recursive - its elements can be similar data structures - and so it goes and so on.
For example, the expression in Chiron's answer, (+ (* 8 8) (* 4 4))
, is converted by the reader into
(clojure.lang.PersistentList
[clojure.lang.Symbol +]
(clojure.lang.PersistentList
[clojure.lang.Symbol *]
[java.lang.Long 8]
[java.lang.Long 8])
(clojure.lang.PersistentList
[clojure.lang.Symbol *]
[java.lang.Long 4]
[java.lang.Long 4]))
Where each element has its type in front of it.
4
are completely evaluated;+
and data structures such as lists are recognized
and constructed. You can see lists representing sub-expressions inside the list representing the whole expression.
Lisp regards each list as the application of the first element - the operator - to the other elements as arguments. So each operator has a number (which may be zero) of elements under it. Thus we think of the hierarchy of lists as a tree.
The read-string
function shows you the structure the reader will produce from a text expression. This isn't informative by itself, as printing it simply reconstructs the text in a standard format.
(read-string "(+ ( * 8 8)
(* 4 4))")
; (+ (* 8 8) (* 4 4))
The function that exposed the structure tagged with its types is
(defn typed [form]
(if (sequential? form)
(cons (type form) (map typed form))
[(type form) form]))
called thus:
(typed (read-string "(+ (* 8 8) (* 4 4))"))