## First Clojure example.

``````
;;; Declarations:
(def n 5)
(defn f[x] (+ x 2))
(f n)
;; Same as above
(def f (fn[x] (+ x 2)))

;;; Clojure collections: Lists, vectors, maps
;; A list
(def numbers '(1 3 -6 7 9))
(first numbers)
(rest numbers)

;; A vector
(def myvec [5 8 9 0])
(first myvec)
(rest myvec)
(seq myvec)
;; creating a vector from a list:
(vec numbers)

;; A hashmap (a map)
(def mymap {:a 6 :b "apple" :c [2 3]})
;; :a is a keyword
(:a mymap)
(mymap :b)
(first mymap) ;; note: the order isn't guaranteed
(rest mymap)
(seq mymap)
(keys mymap)
(vals mymap)

;; Adding an element to a collection using conj (returns the same type of collection):
(conj numbers 6)
(conj myvec 6)
(assoc mymap :x 5)
(conj mymap [:x 5])
(assoc mymap :a 1000)
(conj mymap [:a 1000])

;; Adding a collection of elements using into:
(into numbers ["a" "b" "c"])
(into myvec ["a" "b" "c"])
;; into on a map takes a sequence of key/value pairs
(into mymap [["a" "b"] ["c" "d"]])

;; nil
(first '())
;; the rest of an empty sequence is an empty sequence, not nil:
(rest '())
;;nil is not the same as empty sequence:
(= '() nil)
(nil? '())
;; lookup on a map that doesn't have the key returns nil:
(:x mymap)

;; Functions that work on sequences.
;; A collection is first converted to its sequence, and then
;; the function is applied.
(nth numbers 0)
(nth numbers 4)
(nth myvec 0)
(take 2 numbers)
(take 2 myvec)
(drop 2 numbers)
(drop 2 myvec)
(take 2 mymap)
(drop 2 mymap)

;; Clojure predefined higher-order functions (return sequences)
(map (fn [x] (* x 2)) numbers)
;; you can also write this with a function literal:
(map #(* % 2) numbers)
(filter odd? myvec)
(filter #(< % 4) numbers)
(filter #(not (string? (second %))) mymap)
(reduce + numbers)
;; three arguments for reduce; the second one is used as the starting point
(reduce conj [] numbers)
``````

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.