Skip to content

Instantly share code, notes, and snippets.

;; Approach 1: alter-var-root
(ns play.alter
(:require [play.redef]
[play.internal-use :as int-use]))
(defn use-them []
(int-use/start)
(dotimes [_ 5]
(int-use/foo "work")))
(ns show-clara-bug.core
(:require [clara.rules :refer [defrule defquery insert-all fire-rules mk-session query retract! insert!]])
(:gen-class))
(defrecord Data [id attr])
(defrecord Flag [data-id name])
(defrecord UpdateData [id new-attr])
(defrule the-rule
[UpdateData (= ?data-id id) (= ?new-attr new-attr)]
@visibletrap
visibletrap / stack-trace.clj
Created October 29, 2015 08:32
A convenient function to peek Clojure's stack trace at a certain position in code
(defn stack-traces []
(->> (Thread/currentThread)
(.getStackTrace)
(map (juxt #(.getClassName %) #(.getMethodName %) #(.getLineNumber %)))
(map #(clojure.string/join ":" %))))
@visibletrap
visibletrap / transduce-channel-sample.clj
Last active August 29, 2015 14:25
Transducer บน core.async channel (เหมือน Go channel)
(ns transduce-channel-sample
(:require [clojure.core.async :refer [chan >! <! go-loop go]]))
; เขียน algorithm ให้เลือกเฉพาะเลขคี่แล้วยกกำลัง 2
(def xform
(comp
(filter odd?)
(map #(Math/pow % 2))))
; สร้าง channel ที่มี buffer เป็น 1 แล้ว bind algorithm เข้าไป
(defn trigroup [x]
(let [before (cons nil x)
after (conj (into [] (next x)) nil)]
(map vector before x after)))
@visibletrap
visibletrap / constantize-env.clj
Created May 19, 2015 03:59
[Clojure] convert environ-format environment variables in profile.clj to bash-style environment variables
(defn format-key [k]
(-> k
name
clojure.string/upper-case
(clojure.string/replace "-" "_")))
(defn format-value [v]
(str "\"" v "\""))
(defn constantize-env [env]
(map #(str (format-key (key %)) "=" (format-value (val %))) env))
(ns solve)
(defn ensure-pos [length n]
(if (pos? n) n (+ length n)))
(defn rotate [coll n]
(let [length (count coll)
min-n (rem n length)
lower (ensure-pos length min-n)
upper (+ length lower)]
(defn compress [coll]
(reduce (fn [acc e] (if (= (last acc) e) acc (conj acc e))) [] coll))
; reduce accepts 3 args func, initial and collection, respectively
(assert (= (compress [1 1 2 3 3 3 2 2 3]) [1 2 3 2 3]))
(assert (= (compress [[1 2] [1 2] [3 4] [1 2]]) [[1 2] [3 4] [1 2]]))
(defn stringify [before after]
(if (string? before)
(apply str after)
after))
;; 1
(defn my-replace [coll x y]
(->> coll
(map #(get {x y} % %))
(stringify coll)))
def my_flatten(list)
list.join(',').split(',')
end
my_flatten([1 ,[2, [3, 4], 5]]) #=> ["1", "2", "3", "4", "5"]