|
||
---|---|---|
.. | ||
readme.org |
readme.org
Language syntax
The clojure syntax is super simple it is always a function call followed by arguments, this applies for things like standard conditionals and, or, not etc
All functions return a value, this is always the last statement called inside the function.
When ever you see an opening bracket the value after is always a function unless the bracket is preceded by a character in which case this is a macro a common macro is '(1 2)
which is the same as typing (list 1 2) so a function is still the first parameter.
Basic data structures
In clojure you will find you spend most of your time dealing with lists, vectors, maps and sets each has its own bracket notation in the language you can also call vector
, list
, hash-map
and hash-set
functions to the same effect, how ever it is far more convenient to use the shorthand.
;; lists are denoted with brackets, but remember to use '(
;; or (list function) else the first value is a function call.
'(1 2 3)
;; vectors are donoted with square brackets
[1 2 3 4]
;; hash-maps are denoted with curly braces
;; they must always contain key value pairs.
{:key-one 1 :key-two 2}
;; sets also use curly braces but start with a #
;; sets have to be unique so duplicates will be removed
#{1 2 1 3}
Maths
All maths operators are also functions, meaning you start with the operation then the numbers to apply them against apposed to other languages where you would separate the numbers by operators.
This goes back to function first then arguments.
;; This is equivalend to 1 + 2 + 3 in other languages
(+ 1 2 3)
;; When using multiple operators just nest them.
(* 2 (+ 1 2 3))
Conditionals
Hashmap's keyword's & De-structuring
One of the fundamentals to working with hashmap's in clojure is that keywords are function when ever you see :my-key
you are actually calling a function this is very different to most other languages.
This has some really nice side effects, one being it is very easy to navigate your hasahmap's the example below shows how to pull out the value 2.
Basic value fetching
(def my-hashmap {:top {:first-key 1 :second-key 2}})
;; you can get the value in a number of ways.
;; using neted get return the result of one get to the next
(get (get my-hashmap :top) :second-key)
;; much nicer is to use get-in and specify the path
(get-in my-hashmap [:top :second-key])
;; You can also call the keywords as a function
(:second-key (:top my-hashmap))
;; or using something called a threading macro
;; push the map through the :top function then the result
;; into the :second-key function
(-> my-hashmap :top :second-key)
Wierd symbol's
There is a good reference on the symbols in clojure below when you encounter one your not sure about. https://clojure.org/guides/weird_characters
-> '( #_