Last active
April 24, 2020 01:52
-
-
Save jaidetree/9741849e6c3933a5f4f9439bcb80566e to your computer and use it in GitHub Desktop.
This covers most if not all of Clojure's syntax.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; Comments | |
(comment (any-valid clojure-form :is fine?)) ; end of line comments | |
#_i-am-commented-out "but I am not" | |
;; Values | |
5 3 1/3 0.5 "hello" :keyword | |
;; Lists | |
[1 2 3] ;; Vector - Good for finite, short lists | |
'(1 2 3) ;; seq - Good for infinite, long lists | |
#{1 2 3} ;; set - Good for unique lists | |
{:a 1 :b 2} ;; hash-maps good for pairs requiring lookups | |
;; Calling functions | |
(my-func :operand-a :operand-b :operand-c) | |
my-func ; evalutes to the function | |
#'my-func ; evaluates to a reference to a symbol called 'my-func' | |
;; Atoms are used to track state that changes | |
(def my-atom (atom :yes)) | |
(println (deref my-atom) @my-atom | |
(= (deref my-atom) @my-atom)) ; => :yes :yes true | |
;; Anonymous functions | |
(fn optional-name | |
[a b c] ; arg names\destructuring | |
(println a b c)) | |
; Can't be nested | |
#(println %1 %2 %3) | |
;; Thread Macros | |
; Used to chain outputs and inputs like a pipe operator | |
; Thread first applies the initial value and output as the first argument of supplied forms | |
(-> 5 | |
(+ 2) | |
(- 3)) | |
;; => 4 | |
;; Thread last applies the initial value and output as the laster argument of supplied forms | |
(->> [0 1 2 3] | |
(map #(* % 2)) | |
(mapcat #(range 0 %))) | |
;; => (0 1 0 1 2 3 0 1 2 3 4 5) | |
;; Exceptions | |
; Often better to return data but sometimes interop requires it | |
(try | |
(/ 1 0) | |
(catch Exception e | |
(println e))) | |
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; | |
;; EXAMPLES | |
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; | |
;; Creating a function | |
;; (defn symbol vector & body) | |
(defn my-function ; - It's the same as calling a function like (+ 2 2) | |
[arg-1 arg-2 arg-3] ; - Just a vector, nothing special just regular data | |
(println "arg 1" arg-1) ; - The following forms are executed when the | |
(println "arg 2" arg-2) ; function is ran | |
(println "arg 3" arg-3)) | |
(my-function) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment