Clojure - Syntax

1 minute read

Syntax

Clojure syntax differs from many programming languages in that that it uses parantheses and indentation to construct code. The reason for this is that Clojure is a Lisp, a variant of the Lisp programming language.

Forms

Clojure recognizes two kinds of structures:

  • literal representations of data structures (numbers, strings …)
  • operations

Term form refers to an expression in Clojure.

11
2"hello world"
3["vector" "of" "string"]

Operations are how we do things. They are written as opening paranthesis, operator, operand, closing parantheses

1(operator operand1 operand2 ... operandn)
2(+ 1 2)
3(+ 1 2 6 7)

This style of writing operations is uniform across the whole language unlike a language like JavaScript which uses a mix of notations

Control Flow

if

1(if true
2  "Displays if true"
3  "Displays if false")
4; => Displays if true
5
6(if false
7  "Displays if true")
8; => nil

do

The do operator is used to wrap multiple forms and run each of them.

1(if true
2  (do (println "Success")
3      "Displays if true")
4  (do (println "Failure")
5      "Displays if false"))
6; => Success
7; => Displays if true

when

The when operator is a combination of if and do but with no else branch.

1(when true
2  (println "Success")
3  "boom!!")
4; => Success
5; => boom!!

boolean expressions

Clojure provides all equality testing functions like = or and.

Naming values with def

def can be used to binf a name to a value

1(def a_vector
2  [1 2 3 4])
3
4vector
5; => [1 2 3 4]