Skip to content

Instantly share code, notes, and snippets.

@sw-samuraj
sw-samuraj / blog-concurrency-var-global.clj
Last active March 23, 2017 21:37
An example of Var re-binding (future/global).
(future (def future-var "future var"))
future-var
;; -> "future var"
@sw-samuraj
sw-samuraj / blog-concurrency-var-dynamic.clj
Last active March 25, 2017 17:41
An example of Var re-binding (dynamic).
(def ^:dynamic *dynamic-var* "dynamic var")
*dynamic-var*
;; -> "dynamic var"
(def re-binded-var
(binding [*dynamic-var* "re-binded var"] *dynamic-var*))
re-binded-var
;; -> "re-binded var"
@sw-samuraj
sw-samuraj / blog-concurrency-var-defn.clj
Last active March 20, 2017 21:06
An example of re-binding of the Var containing a composite function.
(defn cube [x] (Math/pow x 3))
(defn cube-root [x] (Math/pow x 1/3))
(defn ^:dynamic prettify [x] (Math/round x))
(defn compute [] (prettify (cube-root (cube 42))))
(compute)
;; -> 42
@sw-samuraj
sw-samuraj / blog-concurrency-var-static.clj
Last active March 25, 2017 17:43
An example of Var re-binding (static).
(def static-var "static var")
static-var
;; -> "static var"
(binding [static-var "re-binded var"] static-var)
;; -> IllegalStateException Can't dynamically bind non-dynamic var:
;; user/static-var clojure.lang.Var.pushThreadBindings (Var.java:320)
@sw-samuraj
sw-samuraj / blog-catalan.clj
Last active March 18, 2017 16:09
Counts a Catalan number through a binomial coefficient.
(defn factorial [n]
"Counts a factorial."
(reduce *' (range 1 (inc n))))
(defn binomial [n k]
"Counts a binomial coefficient."
(/ (factorial n)
(*' (factorial k)
(factorial (- n k)))))
@sw-samuraj
sw-samuraj / blog-catalan-recur.clj
Created March 18, 2017 14:26
Counts a Catalan number through recursion.
(defn catalan [n]
"Counts a Catalan number by recursion."
(loop [cnt n acc 1]
(if (zero? cnt)
acc
(recur (dec cnt)
(* acc (- 4 (/ 6 (inc cnt))))))))
@sw-samuraj
sw-samuraj / blog-map-reduce.clj
Last active March 10, 2017 17:11
Map-reduce snippet for a blog post.
(ns blog-map-reduce.core
(:import java.security.MessageDigest))
(defn digest [string]
"Returns a SHA-1 digest of the given string."
(.digest (MessageDigest/getInstance "SHA-1")
(.getBytes string)))
(defn hex [bt]
"Returns a hexadecimal value of the given byte."