Clojure basics and syntax (10/31/2020)

Languages > Clojure

Comments

Comments can be made after a ‘;’.

Literals

Numeric types

33        ;Integer
-4.6      ;Floating point
1.234E-10 ;Scientific notation
67/4      ;Ratio

Prefixes

0112   ;Octal
0x15A  ;Hexadecimal
2r101  ;Radix (base + r)

Precision

By default, integers are read as fixed precision 64-bits integers if in range, and arbitrary precision otherwise. The floating points values are are read as double-precision 64-bit floats.

Arbitrary precision can be forced:

128N   ;128 is read with arbitrary precision.
3.14M  ;3.14 is read with arbitrary precision.

Special values

##Inf   ;Positive infinity
##-Inf  ;Negative infinity
##NaN   ;Not a number

Character types

"Hello world!"   ;String (can span multiple lines)
\a               ;Character
#"[0-9]"         ;Regexp

Special characters

\newline
\space
\tab

Unicode

\u00C7   ;Hexadecimal unicode
\o307    ;Octal unicode

Symbols and keywords

Symbols

Symbols can be composed of letters, numbers and other characters, and refers to something else, like function, value, namespace…

map             ;Symbol
+               ;Symbol with other character
clojure.core/+  ;Symbol with namespace.

Special symbols

nil             ;Null value
true false      ;Booleans

Keywords

Keywords evaluates to themselves. They can be used as attribute names, enumerated values…

:alpha          ;Keyword
:release/alpha  ;Keyword with namespace

Don’t evaluate symbols or expressions

'x     ;Literally x, and not what the symbol is pointing on.
'(1 2) ;A list containing 1 and 2, and not a call to function 1 with 2 as parameter.

Collections

'(1 2 3)     ;List
[1 2 3]      ;Vector
#{1 2 3}     ;Set
{:a 1, :b 2} ;Map

Def

Def is used to create what is called a “var” by associating a symbol to a value:

(def x 7)
(+ x x)     ;The addition result is 14.

Printing

(println "1 + 2 = " (+ 1 2))  ;Print all the given arguments separated with sapces + '\n' in a "human readable" way.
(print "1 + 2 = " (+ 1 2))  ;Same as println but without final '\n'.
(prn "1 + 2 = " (+ 1 2))  ;Same as println but will show the quotes and will not interpret the special chars (except the final '\n').
(pr "1 + 2 = " (+ 1 2))  ;Same as prn but without final '\n'.

Something to say ?

Leave a Reply

Your email address will not be published.