Skip to content

Instantly share code, notes, and snippets.

@cairesr
Last active August 29, 2016 00:31
Show Gist options
  • Select an option

  • Save cairesr/565ae17ae98bc06f1a3b314cb7ea96fa to your computer and use it in GitHub Desktop.

Select an option

Save cairesr/565ae17ae98bc06f1a3b314cb7ea96fa to your computer and use it in GitHub Desktop.
Clojure: structures

Clojure structure is always the same

(operator operand1 operand2 ... operandn)
(str "you say goodbye" "...and I say hello!")
(+ 1 2)
(map inc [1 2 3 4])

if statement

(if condition
  (statement for true)
  (statement for false) ;; can be ommited, in which case returns nil if falsey
(when true
  (first line of the block
   second line
   .
   .
   .
   n lines for the blocks))

hash-maps

{:name "Rodrigo :age 21} ;; create a hash-map literal
(hash-map :name "Rodrigo" :age 21) ;; create a hash-map through the hash-map function
(get {:a 1 :b 2} :b) ;; => 2
(get {:a 1 :b {:c 2 :d 3}} :b) ;; => {:c 2 :d 3}
(get (get {:a 1 :b {:c 2 :d 3}} :b) :c) ;; => 2
(get-in {:a 1 :b {:c 2 :d 3}} [:b :c]) ;; => 2
(get {:a 1} :c) ;; => nil (for non-existent key)
(get {:a 1} :c "unicorns?") ;; => "unicorns?" (default value)

vector

[1 2 3] ;; => [1 2 3] creates a vector literal
(vector 1 2 3) ;; [1 2 3] creates a vector through the vector function
(vector [1 {a: "opa" b: 1/2} "da string" 23/39]) ;; => [1 {a: "opa" b: 1/2} "da string" 23/39] a vector accepts any type
(get [25 35 300] 0) ;; => 1 (0th element)
(get [25 35 300] 2) ;; => 300 (2nd element)
(get [25 35 300] 3) ;; => nil (there's no 3rd element)
([25 35 300] 0) ;; => 1 (0th element)
([25 35 300] 3) ;; => throws IndexOutOfBoundsException (different behaviour from `(get [25 35 300] 3)`)
(conj [1 2 3] 4 5 6) ;; => [1 2 3 4 5 6] (elements are added at the end of the vector)

lists

'(1 2 3 4) ;; => (1 2 3 4) creates a list literal
(list 1 :simbolo {:name "Cartman" :age 7} 1/2) ;; => (1 :simbolo {:name "Cartman" :age 7} 1/2) creates a list
(nth '(1 2 3 4) 0) ;; => 1
(nth '(1 2 3 4) 4) ;; => throws IndexOutOfBoundException
(conj '(1 2 3) 4 5 6) ;; => (6 5 4 1 2 3) (elements are added at the beginning of the list)

vectors x lists

For a nubie (as I am), the rule of thumb is: use a list when you need to add elements at the beginning of a sequence. Or when you write a macro. Otherwise, use vector. Daniel Higginbotham - Clojure for the Brave and True

sets

Sets are collections of unique elements.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment