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?
ArrayList<int> a = new ArrayList<int>();
a.add(10);
a.add(20);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?
[10 20]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:
(doto (ArrayList.) (.add 10) (.add 20))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:
#arraylist [10 20]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?
2
3
u/jaihindhreddy Apr 23 '20
Nice to see the explanation helps. I would have polished it more if it were to be public 😅
I found Rich Hickey's "Clojure for LISP Programmers" talks extremely useful too. And of course, SICP and HTDP are excellent resources that are a bit more general, using Scheme and Racket respectively.
3
u/LeSUTHU Apr 23 '20
Hey Hello
I was going to tell you about posting it here. I hope you don't find it rude of me... I think I forgot after some time. I personally have never seen such an easier description of this concept, so I sent it to one of my friends, and they loved it, so I decided to post it here so everyone could see it.
You should be proud how much people enjoyed your response tho.
Sorry again that I didn't ask for permission first... :(
2
u/jaihindhreddy Apr 24 '20
I don't find it rude at all 😄! I'm happy if it helps others.
In a mentor-mentee context, further discussion is handy, whereas it would have to be more polished so that it's more self-explanatory and/or points to other resources which when combined becomes self-explanatory. That's the only thing that irks me a little 🙂
2
u/LeSUTHU Apr 24 '20
Oh. I should have notified you prior to see if you had any edits you wanted to make...
I cannot speak for other or for you, but I found this piece of description much more helpful than the other articles I have read before. :D
3
u/yubrshen Apr 23 '20 edited Apr 24 '20
Now, you're mentors to many of us. I never had such a clear explanation of the macros' mechanism before.
Thanks again!
3
u/yubrshen Apr 23 '20
Now your mentor becomes mine! Thanks to Mentor and you!
Just want to confirm more detailed understanding:
In the following,
"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."
Perhaps you mean that if with its 3 arguments are not evaluated as a normal function.
With a normal function f, (f a b c) would first evaluate a, b, and c, then the application of f with the evaluated results.
but for special form (if condition then else)
the evaluation would be
eval condition
based on the condition's evaluation, select to evaluate then or else. (then and else parts will never be evaluated both)
3
u/LeSUTHU Apr 23 '20
Yes I believe that's correct.
So while they all share the list structure, I assume that under the hood, how it evaluates and return stuff would be slightly different compared to other non special case functions.
3
u/LeSUTHU Apr 24 '20
Another thing that I just thought of is that. Functions will go through the whole body before it returns a value. So whatever is in the function body, it will be run.
But for if statements, if you think about it, it's like a crossroad, and only one part of it gets executed and the other side is totally ignored.
2
u/jaihindhreddy Apr 24 '20
Right! In fact, the only conditional evaluation construct is the `if`. Because macros have a lot of expressive power, everything else, like `or`, `and`, `cond`, `if-not` etc. are implemented using `if`. Try `(macroexpand-1 '(or 1 2))`.
And `quote` prevents evaluation completely.
5
u/pavelklavik Apr 22 '20
A nice write-up, I have added a link to this in my Clojure introduction: https://orgpad.com/o/fa4eb667-cbbb-4d85-8a96-ca0cdac7b5b1. As a beginner, I wouldn't spend much time with "code as data" and macros in general: you don't really need them unless you are writing some low level libraries and macros have disadvantages like making the code harder to understand.
For me, the main advantage of Clojure is that it is data oriented, you mostly program using data structure and their transformations which is much preferable to data composition. Also REPL gets much more useful, since every output of REPL can be copied and inserted back into REPL or copied into the code. There is no easy way to output data structure in, say, Java, and get a code from it. Since data structures can be easily created in the code, they are much more used.
1
Apr 22 '20
Please use four space indentation for code blocks. Reddit poorly understands 3 backquote blocks
2
u/LeSUTHU Apr 22 '20
Oh sorry I didn't thought of that. I just copied what my mentor has sent me and pasted it here but I'll make the edit
2
Apr 22 '20
It also seems that you're using Fancy Pants Editor, and it escapes backquotes, so all your inline code looks like `this` and not like
this3
u/LeSUTHU Apr 22 '20
Is that bothering you too much? I could change if you want, but I personally don't think that the layout matters but not too much and it is still quite readable. Obviously I am generalizing and if people think differently, I would change.
But tbh, I don't think I want to basically waste like 5 minutes of my time, just to make these changes.
2
Apr 22 '20
I adhere good formatting both in code and in documents :)
I'm not forcing you to change, just pointed out that you may want to pay attention to what mode you in. I see so many incorrect formatting on Reddit since they made Fancy Pants Editor the default, and made it escape markdown for some weird reason...
2
u/LeSUTHU Apr 22 '20
Oh I see.
I do agree with you. Good formatting is I think should be required, as especially for me like beginners, worse documentation costs me hours more than it should really take. For this situation tho, I thought that the formatting was actually already decent..
2
Apr 22 '20
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.
I liked this simple code-as-data example:
(def image-type 'svg)In simple words, here we bind a name svg to the image-type. This name by itself is code, but at this point it doesn't have value bound to it, so it is just code. If we were to do this in python, we would create a variable
# image types
svg = 0
image_type = svgHowever here we're using data held by that svg variable, not the code, an in Clojure example.
Now of course such concept as name does not exist in computer world, so we're still storing data under the hood. I guess we could have stored pointer in C, and say that this is code-as-data too, but high abstractions of Lisp and ability to disable evaluation to treat code as data is what separates Lisps from non-Lisps.
2
u/jaihindhreddy Apr 24 '20
Absolutely! In fact, in Clojure (not ClojureScript), we can touch the name, the variable and the value in the variable separately. When we type (def a 1). `'user/a` gives us the name, `#'user/a` gives us the variable and `user/a` gives us the value.
5
u/TheMagpie99 Apr 22 '20
Trying to learn common lisp at the moment to this explanation really helps! Thanks for posting!
Also, how good are the mentors on exercism? So glad I found that a few months ago and have had really useful feedback on a variety of language tracks!