Skip to content

Instantly share code, notes, and snippets.

@andrewvida
Last active December 29, 2015 03:08
Show Gist options
  • Save andrewvida/7605176 to your computer and use it in GitHub Desktop.
Save andrewvida/7605176 to your computer and use it in GitHub Desktop.
Clojure notes

Nuggets of Clojure

Data Structures

Core data structures are immutable

  • Numbers

    43
    6.7
  • Strings

    • only double quotes
    • no string interpolation; concat using str
    (println "Lord Voldemort")
    (println "\"He who must not be named\"")
    (println "\"Great cow of Moscow!\" - Hermes Conrad")
  • Maps

    • like dictionaries or hashes in other languages
    {:a 3 :b 4 :c 18 }
    • lookup
    (get {:a 3 :b 4 :c 18 } :b )
    ; => 4
    
    (:b {:a 3 :b 4 :c 18 })
    ; => 4
    
    (get mymap {:a 3 :b 4 :c 18 } )
    (:b mymap)
    ; => 4
  • Keywords

    • primarily used as keys in maps
    :a
    :spongebob
    :andy
  • Vectors

    • similar to an array in that it's a 0-indexed collection
    [3 2 1]
    
    (get [3 2 1] 0)
    ; => 3
    
    ;; Another example of getting by index. Notice as well that vector
    ;; elements can be of any type and you can mix types.
    (get ["a" {:name "Andrew Vida"} "c"] 1)
    ; => {:name "Andrew Vida"}
  • Lists

    • similar to vectors in that they're linear collections of values. You can't access their elements in the same way, though:
    ;; Notice the leading single quote
    '(1 2 3 4)
    
    ;; Doesn't work for lists
    (get '(100 200 300 400) 0)
    ;; This does
    (nth `(100 200 300 400) 3)
    ; => 400
    
  • Sets

    • Unique sets of values
    #{"Andy" "Jennifer" 3 }
    
    (get #{"Andy" "Jennifer" 3 } 3 )
    ; => 3
    
    ;; If you try to add "Andy" to a set which already contains "Andy",
    ;; the set still only has one "Andy"
    (conj #{"Andy" "Jennifer" 3 } "Andy" )
    ; => #{"Andy" "Jennifer" 3 }
    
    (get #{"Andy" "Jennifer" 3 } :a )
    ; => nil
    
  • Symbols

    • Identifiers that are normally used to refer to something. Let's associate a value with a symbol:
    ;; my-family is a symbol
    (def my-family
      [ "me"
        "wife"
        "kids"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment