Skip to content

Instantly share code, notes, and snippets.

(defn mapify
"Return a seq of maps like {:name \"Edward Cullen\" :glitter-index 10}"
[rows]
(let [;; headers becomes the seq (:name :glitter-index)
headers (map #(get headers->keywords %) (first rows))
;; unmapped-rows becomes the seq
;; (["Edward Cullen" "10"] ["Bella Swan" "0"] ...)
unmapped-rows (rest rows)]
;; Now let's return a seq of {:name "X" :glitter-index 10}
(map (fn [unmapped-row]
;; Given a vector of headers and a row, make a key-val pair for each column
(defn pair-cols
[headers columns]
(into {}
(map
(fn [header column] [header ((get conversions header) column)])
headers columns
))
)
(defn mapify
(defn comp1
([]
;; No functions provided, return identity
identity
)
([f]
;; A single function provided, return itself
f
)
([& fs g]
(defn tri*
"Generates lazy sequence of triangular numbers"
([] (tri* 0 1))
([sum n]
(let [new-sum (+ sum n)]
(cons new-sum (lazy-seq (tri* new-sum (inc n))))
))
)
(defn tri1*
"Generates lazy sequence of triangular numbers"
(defn testcond
[a]
(
cond
(a > 10) "Greater than 10"
(a > 100) "Greater than 100"
else: "Very big!"
)
)
;; future runs on another thread, so it's asynchronous
;; in this case it returns
;(future (#(deliver result %&)
; (+ 8 7)
; (- 8 7)))
(defn call-service
[arg1 arg2 callback-fn]
(future (callback-fn (+ arg1 arg2)
(- arg1 arg2)))
)
(defn echo-watch
[key identity old new]
(println key old "=>" new))
(def sarah (atom {:name "Sarah" :age 25}))
(add-watch sarah :echo echo-watch)
(swap! sarah update-in [:age] inc)
@kindlychung
kindlychung / concurrency.clj
Created January 18, 2015 16:45
Clojure programming book, examples code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Some code from Clojure Programming book [Chas Emerick et al.]
(def d
(delay (println "Running...") :done!)
)
(deref d)
@d
(defn get-document
[id]
;; compound interest with the -> macro
(defn final-amount-> [principle rate time-periods]
(-> rate
(/ 100)
(+ 1)
(Math/pow time-periods)
(* principle)))
(final-amount-> 100 20 1)
@kindlychung
kindlychung / 1.clj
Created January 20, 2015 16:36
Benchmark of (function literal) (partial) and (function literal with apply) in clojure
(use 'criterium.core)
(def f1 (fn [x] (str "hello, " x)))
(def f2 (partial str "hello, "))
(def f3 (fn [& args] (apply str "hello, " args)))
(f1 1)
(f2 1)
(f3 1)
(bench (f1 "victor"))
(bench (f2 "victor"))
(bench (f3 "victor"))