Now we understand the basics is time to delve into the language. As we study the language is recommended that you also use the REPL to follow the code examples (and you can use an online REPL if you want to).
Syntax
As we know Clojure is a LISP and in all of its dialects what draws attention when we're reading the code is the parenthesis. In fact, when we're talking about LISP most of our code is written using parenthesis in what we call form or expression (for simplicity we can adopt form).
Image: "Form composition" made by the author is copyleft material under unlicense.
- operator is an operation that receives arguments and produces a result.
- ...args is one or more arguments that are consumed by the operator.
In fact, Clojure as a LISP only supports two structures:
- Data is the literal representation of values.
- Forms.
For example when we enter a form like:
(+ 3 4 5)
=> 12
The form is composed of the operator (the function +) and the arguments (3 4 5) that are arguments passed to the function and produce 12.
This at first glance may look strange, but Clojure (and LISPs) have uniformity in its syntax. When someone programs in Java there are operations with different syntax depending on the operation and operands while in Clojure everything has always the same structure.
Evaluation
When we work with Clojure is frequent that part of the arguments of the form is other forms. As example:
(+ 5 6 (- 8 4))
=> 15
More complex forms are evaluated as follows:
Image: "Clojure form evaluation" made by the author is copyleft material under unlicense.
Data
If we append a form with apostrophe ' then the form is evaluated as data.
'(+ 1 2 3)
=> (+ 1 2 3)
When the form is evaluated as data the computer will not execute it, instead, it will return it as plain old data which we can use to perform operations on code.
This is one of the main advantages of LISP dialects over most programming languages that are mainstream. In LISP there's a concept known as homoiconicity where code is data and data is code.
The use of an apostrophe to treat forms as data is called quoting. When we quote our form everything on it is ignored and treated as a simple list containing data (and lists will be our next subject).
Let's continue the Clojure Quest
Now we started to mess with code we're barely starting. Clojure is a great language with so much yet to see and we will continue our quest to master it in the next post on this series hope have you there too.
Top comments (0)