r/Clojure • u/LeSUTHU • Apr 22 '20
"Code as Data" Beginner Oriented
Hello everyone, I am a clojure beginner and I was doing some exercises on exercism.io. I asked my mentor, what did "code as data" mean as I just hear that all the time with Lisp, but I didn't understand it really well.
He returned a gigantic reply, which was really easy to understand and I think sums the whole thing up nicely. I'm sure a lot of you are already familiar with this concept, but I thought it would be great to share his response, in case you want to pass this again to other clojure (and Lisp) beginners.
======================================================
I hope you got time, cuz this is gonna take a while 🙂
Let's say you have a file of Python code `p.py` and a file of Clojure code `c.clj`.
In one sense, all code is data, even Python code. The `p.py` file has some bytes. Takes up space, can be stored, compressed, emailed, printed on a paper, etc. It is data. What people say, "In LISPs, code is data", they mean "LISPs are homoiconic". Homoiconic means the syntax of the language is defined as the interpretation of the data structure literals of the same language.
For example, in JavaScript, `[1, 2, 3]` it the syntax for an array literal, whereas you can also write it this way, `Array(1, 2, 3)`. Look at the following piece of JavaScript:
const a = 'foo';
const b = [1, 2, 3];
const c = 40 + 2;
const d = f(4);
const e = (1 > 2) ? 'wat' : 'okay';Now, there are clearly some data structure literals in here, `'foo'` is a string, `[1, 2, 3]` is an array of numbers, `40`, `2`, `4`, `1` are numbers and `'wat'` and `'okay'` are strings. But, what is `const`? What are those `a`, `b`, `c`, `d` and `e` things. What's `=`? What's `;`. These are not JavaScript data structure literals. These are pieces of text. Those `a`, `b`, `c`, etc do have names. They are not nothing. They are called identifiers. But, can you store an identifier in a variable, in JavaScript?
First a small recap of Clojure data-structure literals:
;; Nil
nil
;; Bool
true false
;; Ints
1 2 3
;; Bigints
1N 2N -3N
;; Floats
1.0 2.3
;; Big Decimals
1.432M 2.3M
;; Characters
\a \b \space \newline \n \g
;; Strings
"ab" "I am a string" "I'm also a string"
;; Symbols
a b c foo bar + even? ns-qualified/hyphens-are-fine
;; Keywords
:a :b :c :foo :bar :+ :even? ::can-be/ns-qualified-too!
;; Lists
(1 2 3) () (a 3 2) (() ())
;; Vectors
[] [1 2 3] [()]
;; Sets
#{} #{1} #{#{1}}
;; Maps
{} {:a 1 :b 2} {[1 2] [3 4]}
;; Regexps
#"a?b" #"^[^()]*$"And now, let's look at a similar piece of Clojure code:
(def a "foo") ; List with symbol def, symbol a, and string "foo"
(def b [1 2 3]) ; List with symbol def, symbol b, and a vector with ints 1, 2 and 3
(def c (+ 40 2)) ; List with symbol def, symbol c, and a list with symbol + and ints 40, 2.
(def d (f 4)) ; List with symbol def, symbol d, and a list with symbol f and int 4.
(def e (if (> 1 2) "wat" "okay")) ;; You get the point.Anything and Everything in this piece of code is a Clojure data-structure literal. This is precisely what people mean by "code is data". By itself, it isn't very profound. But it makes macros way easier and this is where things get crazy.
To understand macros, we need to look at how evaluation is done. For example, in JavaScript, you type a piece of code and press enter. What happens then is, the code is parsed into an Abstract Syntax Tree (AST) based on the grammar of the language, usually defined with BNF. Then some optimisations are done, then the AST gets transformed into lower-level code and then is run. Whereas in Clojure, there are two distinct steps that happen. They are **read**, and **eval**. The first step is **read**. The text you type in is **read** by the **reader**. And once the reader is done with it, what you have is data. There's no more text. For example, let's say you entered `(if true 1 0)`, that's a 13-character string i.e, text that you entered. That goes into the reader, and out comes a list with the symbol `if`, the boolean `true`, the int `1` and the int `0`. And not **eval** is done.
For everything except symbols and the collections, **eval** is the identity function. In other words it just returns the thing.
For symbols, **eval** looks up the value that symbols is bound to, in that particular context.
For maps, vectors and sets, **eval** evaluates each thing inside them and then returns the thing. In other words `[(+ 1 2) (- 2 1)]` evaluates to `[3 1]`.
For lists, it considers the first thing as the verb, and the rest of the things as the arguments to the verb. In other words, the first thing is "what are we doing?", and the rest of the things are "what are we doing that with?". Now, the reason I said verb and not function is, not everything can be a function. For example, `if` cannot be a function. If we run `(if true (println "true") (println "false"))`, only one thing is printed whereas if `if` was a function. Then both would have been printed. The verb can belong to one of three classes. It's a function, a macro, or a special form. `if` is a special form. `+` is a function.
Now the only missing piece is a macro.
A function is nothing but a data transformation i.e, something that takes in one piece of data, thinks about it, and returns another piece of data.
Now, we've already established the fact that Clojure code is represented as data. And if we can manipulate data with functions, we can manipulate code (as data) with functions. And that's precisely what happens.
The first step of **eval** is macroexpansion. It there's a list with the first thing being a symbol that points to a macro, the arguments are given to it **before evaluation**. And whatever data the macro returns is treated as code, and this code is macroexpanded again. This essentially means you can have a full two-way dialogue b/w the compiler/runtime and manipulate code to your hearts content.
For example, let's say Clojure didn't have `if-not`, and we want to add it. For example `(if-not a b c)` should be transformed to `(if a c b)`. That's a fn that takes 3 things and returns a list. You'd write it this way:
(defmacro if-not [test then else]
(list 'if test else then))I'm returning a list with the symbol `if`, and the last two args reversed. And that's it! We have `if-not`
Now, if you're observing closely, you might already have guessed that I'm (over)simplifying things. I was. The piece of code above that defines `if-not` is not *entirely* data. There's a single quote there. What is that? That's not a piece of data. In fact, when we say "Clojure code is data", what we write in some Clojure file is not directly data. Clojure has a 2-phase syntax. The first phase is define in terms of text whereas the second phase is defined in terms of data. What I've ignored until this point is the first phase. `'a` is syntax sugar for `(quote a)`. `quote` is a special form whose evaluation semantics are "return the thing unevaluated". The Clojure reader knows all about the first phase of syntax, and the Clojure compiler (impl of `eval`) has no clue about it. The compiler only deals with data. You can verify this by trying `(read-string "'a")` in your REPL. Also try it on `@a` and `#(+ % %2)`. In general, whenever you look at a piece of code, and can see that it's not data, call `read-string` on it, and it will become data.
Because macros are such powerful constructs, the core LISP interpreter/compilers can be made extremely small. There are a tiny number of special forms in Clojure (somewhere around 10 I think). Everything else is a macro, or a function.
Macros also allow users of the language to extend the language itself, and share such language extensions as libraries.
Now, this doesn't mean code cannot be manipulated in non-LISPs. In python for example, the standard library has an `ast` module using which you can manipulate code. But you'd have to learn the format of the AST, essentially holding the entire grammar in your head. Whereas in Clojure (and LISPs in general), all you need to know are "how do read and eval work?", and everything else from there is discoverable. Because of the uniform syntax, you can learn things, one macro at a time, by studying it's source code, which is in the same language, and manipulates the data structures of the same language.
Hope I was clear. Feel free to ask for any clarification, or any other questions you have.
Have a nice day!
PS: Phew, that took a while. The quote is one character, but there's so much backstory to this. Also check out Rich Hickey's [conversation with Brian Beckman](https://www.youtube.com/watch?v=wASCH_gPnDw) and his Clojure for Java Programmers ([Part1](https://www.youtube.com/watch?v=P76Vbsk_3J0), [Part2](https://www.youtube.com/watch?v=hb3rurFxrZ8)). This explanation combined with those talks should probably put all the pieces together.
5
u/didibus Apr 22 '20
That's a great explanation for it.
It helps me to think of what homoiconic means as well. Homo means same. And iconic means icons. Same icons. That means, the code and the data use the same icons, the same exact textual representation for one and the other. Thus you represent data and code in text the same way, using the same syntax.
One more thing I want to add, there are more benefits to homoiconicity then just macros.
Another one of the big benefits is that not only is code data, but data is code as well! Remember, same icons! This means that serialization of data is trivial.
In Java for example, how do you serialize an ArrayList?
This is the code for an ArrayList of 10 and 20, but when you try and print this or serialize it, you don't get this code back. With default printing and serialization you get some binary representation. If you use a JSON serialization library then you get JSON back, and JSON is not valid Java code. So you also need a custom deserializer to read it back into Java.
What about Clojure?
That's the code for a vector of 10 and 20. When you print or serialize it you just get this code back. So when you want to deserialize it, you just need to tell Clojure to read it back as code.
JavaScript actually has data as code, and people often call it JSON (Javascript object notation). But Javascript doesn't have code as data. Not quite fully homoiconic, but it is partially homoiconic in that data and code for that data are same, but not all code is data. But you still get some of serialization benefits I mention with it.
Some of the serialization benefits JavaScript doesn't get are when you want to serialize data which doesn't have a standard notation in JavaScript.
In Clojure, for example, a Java ArrayList is:
Now this is already data, so you could just serialize it as a list, and when you read it back Clojure will recreate an ArrayList of 10 and 20 for you. But Lisps have another trick, reader macro. In Clojure the version of reader macro you get is called tagged literal. It is a data notation which is user extendable.
So while the ArrayList code is list data, it's not a very compact or clean literal representation, and feels a bit weird to use for serialization. But with tagged literal, you can just create the missing literal yourself:
The above is valid Clojure code, and it is also a literal representation of an ArrayList in Clojure. Now this is a pretty nice way to serialize an ArrayList wouldn't you say?