Hello young Lisper! In this article, you will learn how Lisp code works, what the main data types are, and what it means for code to be evaluated.
I will be using Clojure from now on. Its syntax is modern and easier for beginners to pick up, with literal syntax for common collections and other helpful features. Most importantly, it uses fewer parentheses, which makes it less intimidating at first. In the previous article of the series, I compared the most popular Lisp dialects and gave a quick reference on where to start with each of them.
Let’s start the journey into Lisp by printing a “Hello World” string. To run this code (in Lisp, we say evaluating code), press the play button. You can also experiment on your own by editing and re-evaluating the code. The rest of this guide expects you to evaluate each runnable code block in order to follow the explanation.
println is a function that prints objects to standard output. In this case, we passed a string to it and it printed it to the screen. The last value, nil (Lisp’s version of null), is what the evaluation returned. Every expression in Lisp evaluates to some result, so when a function has no meaningful value to return, it returns nil.
Let’s see what happens if we pass different arguments to println.
println behaves as we would expect. The last example printed a map, a hash-map data structure built into the language, similar to a dictionary in Python. I’ll discuss data structures further in the next article of the series.
Now let’s see what happens if we try to print another of Lisp’s data structures: a list. A list is visually represented as elements enclosed in parentheses and separated by whitespace, like (a b c).
In this case, Lisp didn’t print the argument verbatim as before. Instead, it printed a value: 3. This is because Lisp executed the + operation on the arguments 1 and 2 and printed the result (3).
This happened because lists in Lisp are used both as a data structure and as a representation of executable code. (+ 1 2) is a list of three elements (+, 1, 2), but it also invokes the function + with 1 and 2 as arguments.
To be precise and distinguish between the two, the term list refers to the underlying data structure, which in Lisp is usually a singly linked list. The syntax used to write those lists, along with everything else in Lisp, is called an s-expression.
S-expressions
Everything in Lisp is written as an s-expression, a recursive structure that is either an individual atom or a parenthesised list containing zero or more s-expressions.
1 ; atom() ; empty list(+ 1 2) ; list containing 3 atoms This definition is recursive because a list can contain other s-expressions, forming nested lists as we saw in the previous code example.
In Lisp, both code and data are written using s-expressions and parsed into the same underlying data structures. Because a program’s syntax tree is represented directly with the language’s own native data types, Lisp code can inspect, generate, and transform other code using standard data-manipulation functions. This property is called homoiconicity and is famously associated with Lisp.
We can distinguish code from data using the same s-expression in an example.
In the first case, the parentheses group an operation (+) and its arguments (1, 2) together, so when the list is evaluated by Lisp, it returns the sum of its arguments. That’s a list treated as executable code.
In the second case, the character ' in front tells Lisp that the expression is “quoted”, which means it should be treated as a list data structure rather than evaluated. This is why the list returns itself. That’s a list treated as data.
Atoms and data types
In Lisp terminology, atoms are distinct units that represent everything that’s not a list. The following are the basic data types of Clojure, as well as valid examples of atoms.
nil ; null value123 ; integer123e4 ; scientific notation12.3 ; double1.23M ; big decimal22/7 ; ratio"lisp" ; string\a ; character#"\d+" ; regextrue ; booleanfalse ; boolean Alongside to these standard types, Lisp relies heavily on two distinct symbolic types: keywords and symbols.
Keywords are symbolic values that always begin with a colon : and evaluate to themselves. Keywords are interned, which means each unique keyword points to a single instance in memory, making equality checks nearly instantaneous. They are commonly used as keys in maps or as identifiers.
Symbols represent names, such as variables, functions, or operators. If we evaluate a symbol, Clojure tries to resolve it, which means it will look for the value that the symbol represents.
To use a name as a symbol, we need to prepend the quote character ', which tells Lisp not to resolve the symbol, exactly as we did for the list in the previous section.
Unlike in most languages where a variable name only exists in your source code, a Lisp symbol is a real value you can store in a list, pass around, and inspect. Treating names as ordinary data is a big part of what makes Lisp macros possible. We will explore macros further in the series, once we’re more comfortable with the fundamentals of the language.
Now we are able to describe what Lisp sees in a snippet like the following:
(+ 1 2) An s-expression that takes the form of a list composed of a symbol and two numbers.
Forms
S-expressions that can be evaluated as code are called forms. With this concept, we can state our first syntax rule: Lisp code is structured as a series of forms.
The following is a single form made up of nested forms. Together they evaluate to the number 42, which — since it is an atom — is a valid form itself.
We can introduce a semantic rule for Lisp: a valid form is an atom, an empty list, or a list whose first element is an operator.
This means that not all s-expressions are valid forms. The following is a valid s-expression, but throws an error when evaluated because "plus" is a string and therefore cannot be invoked as a function.
Atoms forms, excepts symbols are evaluated to themselves.
A symbol form, on the other hand, is treated as the name of the variable it refers to. When evaluated, Lisp tries to resolve the symbol-variable association by looking up the value in the current scope. If it can’t, it will throw an error.
In the example below, the symbol x does not have anything associated with it yet.
To avoid the error, we need to associate something with the symbol. def allows us to do exactly that. It takes a symbol and associates the value returned by the second form with it. The association between a symbol and a value (including a function) is called binding.
In this case, we bind the symbol x to the function +. Evaluating x will then return the value of the new binding (the function +), making it usable in normal expressions.
List forms, instead, are evaluated in three distinct ways: function call forms, macro forms, and special forms. What determines which way is used is the first element of the list, which names a function, a macro, or a special operator.
For function calls, the first element does not have to be a hardcoded symbol. Functions are first-class values in Lisp, meaning they can be returned from expressions just like numbers or strings. Any form that evaluates to a function can be the first element.
In the example below, the inner form starting with if evaluates to a function (+ or -) that is then used to compute the mathematical operation. Whether it will be an addition or a subtraction depends on the value of v. Try changing the value of v to another number and re-evaluating to see what happens.
Function calls and signatures
We already performed a few function calls in the previous code examples, like addition (+), multiplication (*), or printing to the screen (println). For this reason, it’s worth introducing the syntax specification (signature) for a generic function call in Lisp.
(function-name argument*) Lisp uses prefix notation for calling a function. In Lisp, signatures tell the user what arguments a function, macro, or special form expects.
Signatures use a set of symbol conventions derived from regular expressions:
*: Zero or more of the preceding item.?: Zero or one of the preceding item (so it’s optional).+: One or more of the preceding item.
One big advantage of prefix notation is that it is never ambiguous. Take a standard infix expression like 6 / 2 * 3. On its own, it can be read in two different ways: either (6 / 2) * 3 (which is 9) or 6 / (2 * 3) (which is 1). To resolve that ambiguity, infix languages usually use some operator precedence rules.
In Lisp, you cannot write expressions that are ambiguous. You always have to be explicit about which operation runs on which values.
This also shows a new rule that Lisp follows for every function call: all arguments are evaluated before the function itself is executed.
Special forms
The most attentive readers have probably noticed something in the example above that does not work quite as expected. We said that the arguments of a function are evaluated before the function is executed, so why do we only see one string printed and not two? There are two println calls inside the if statement, so both should be executed. Well, this is because if is not a function, but a special form.
Special forms are language constructs that are built into the compiler. They have their own evaluation rules instead of behaving like a normal function call.
Unlike a regular function, if evaluates only one of its two branches, depending on the condition. Let’s see its signature.
(if test then else?) Evaluates test and if it’s value is not nil or false, evaluates and yields then; otherwise, evaluates and yields else. else is optional, if not supplied it defaults to nil.
Let’s also see the signature of another special form that we used previously: def.
(def symbol doc-string? init?) def creates a global variable named symbol. init is optional: if supplied, Clojure evaluates it and assigns the result to that variable; if you leave init out, the variable is created without a value. doc-string is an optional documentation string attached to the definition (note that it can only be included when init is also provided). def returns the variable itself rather than the value stored inside it.
The following are all valid uses of def.
(def empty-sym)(def sym-with-val 42)(def full-def "Doc-string" 13) Clojure has 19 special forms, while Common Lisp has 25 of them. We will encounter more later in the series.
Reader and Evaluator
The two fundamental elements that define a Lisp compiler are the reader and the evaluator.
The reader is the part of the compiler that transforms source code from strings into Lisp data structures (like lists, symbols, and numbers). The evaluator takes those data structures and evaluates them using the language’s rules to produce a result.
These two parts in Lisp are exposed directly in the language and can be used in our programs. Let’s test how a string is read into a list and then evaluated.
The evaluator’s purpose is to evaluate an expression within the current environment. For now, think of an environment as the set of symbols and their associated values or functions available to the program. In the environment where you executed the code above, the symbol + was bound to a built-in addition function. Otherwise, evaluating the expression would have thrown an error.
The reader’s job of converting strings into Lisp objects is roughly equivalent to the combination of a lexer and a parser in other languages, which process source code and produce an Abstract Syntax Tree (AST). An AST is an internal data structure that is generally not directly accessible or easily manipulated from within the language itself. In contrast, Lisp represents code using the same data structures it uses to represent ordinary data.
Visualise the code
Now, after this basic introduction to the language, I want to quickly tackle the parentheses issue that many programmers like to complain about when approaching Lisp code.
To let the answer emerge, let’s define a new function greet that prints a welcome message if the argument s is a string. Don’t worry about the syntax right now. I will explain how functions are defined in more detail later in the series. Just notice how a simple function is written as a series of nested forms with many parentheses.
We can visualise the various forms using different colour blocks. This can help you grasp how a Lisper sees the code, instead of seeing a large mass of parentheses.
defn greet [s]
if string? s
println str "Hello " s
println str "Greet requires a string. Received " type s The answer is that once you get comfortable reading Lisp code, parentheses will disappear. Something will click in your mind and you will make sense of them. You will learn to write code as a series of nested forms, and they will help you clearly understand the scope in your code.
Most editors have plugins to help beginners manage parentheses, such as rainbow parentheses, Parinfer, and Paredit. You can also use an extension like Calva for VS Code, which comes ready to work with Clojure out of the box.
Wrap-up
For a programmer, it’s usually faster to read code directly than a wall of text.
;; Atoms: everything that is not a list (evaluate to themselves, except symbols)nil ; null value123 ; integer123e4 ; scientific notation12.3 ; double1.23M ; big decimal22/7 ; ratio"Lisp" ; string\a ; character#"\d+" ; regextrue ; boolean (also false):k ; keyword (interned, evaluates to itself)'sym ; quoted symbol (treated as data, not resolved)
;; Bindings: associating a symbol with a value (returns the var, not the value)(def x 10) ; => #'user/x(def y "Optional docstring" 5) ; => #'user/y
;; S-expressions & Quoting: code vs. data() ; empty list (valid form) => ()'(+ x 5) ; quoted list (treated as data, not evaluated) => (+ x 5)
;; Forms & Function Calls: prefix notation (function-name argument*)(println "Hello") ; prints Hello to standard output => nil(+ x (* 2 3)) ; nested forms => 16((if (= x 10) + -) x y) ; functions are first-class values => 15("plus" 1 2) ; valid s-expression, invalid form (throws an error)
;; Special Forms: built-in compiler rules (e.g. if, def)(if (= x 10) "Only this branch is evaluated" (println "This is never executed")); => "Only this branch is evaluated"
;; Reader, Evaluator & Homoiconicity: strings -> Lisp data -> evaluated result(def form (read-string "(+ 1 2)")) ; reader turns source text into a listform ; => (+ 1 2)(eval form) ; evaluator runs the list in the current environment => 3