Skip to content

Instantly share code, notes, and snippets.

View astrangeguy's full-sized avatar

astrangeguy

  • base engineering GmbH
  • Hamburg, Germany
View GitHub Profile
(def fib-var-obj
(fn [x]
(if (< x 2)
1
(+ (fib-var-obj (- x 1))
(fib-var-obj (- x 2))))))
(defn fib-lex-obj [x]
(if (< x 2)
1
(def foo (fn foo [x]
(if (zero? x)
x
(foo (dec x)))))
(dotimes [i 3]
(println "lexical binding run" i)
(time
(dotimes [i 1000]
(foo i))))
(ns strangeness.fn-arity
(:import java.lang.reflect.Method))
(defn declared-methods [^Class class]
(filter #(= class (.getDeclaringClass ^Method %))
(.getMethods class)))
(defn has-arity? [fun arity]
(let [cls (class fun)
methods (declared-methods cls)]
(ns strangeness.fn-arity
(:import java.lang.reflect.Method))
(defn declared-methods [^Class class]
(filter #(= class (.getDeclaringClass ^Method %))
(.getMethods class)))
(defn has-arity? [fun arity]
(let [cls (class fun)
(import java.util.concurrent.LinkedBlockingQueue
java.util.concurrent.atomic.AtomicReference)
(defn pipe []
(let [q (LinkedBlockingQueue.)
qr (AtomicReference. q)
NULL (Object.)
END (Object.)
produce (fn produce
([item] (if-let [^LinkedBlockingQueue q (.get qr)]
(defmacro my-defrecord
[name [& fields] & opts+specs]
(let [gname name
[interfaces methods opts] (#'clojure.core/parse-opts+specs opts+specs)
classname (symbol (str *ns* "." gname))
tag (keyword (str *ns*) (str name))
hinted-fields fields
fields (vec (map #(with-meta % nil) fields))]
`(do
~(#'clojure.core/emit-defrecord name gname (vec hinted-fields) (vec interfaces) methods)
(defmacro my-defrecord [the-name [& fields] & opt+specs]
(let [full-classname (symbol (str (.name *ns*) \. the-name))]
`(do
(ns-unmap *ns* '~the-name)
(defrecord ~the-name [~@fields] ~@opt+specs)
(ns-unmap *ns* '~the-name)
(defn ~the-name
([~@fields]
(new ~full-classname ~@fields nil nil))
([~@fields ~'meta ~'extmap]
(defn label* [thunk]
(let [NONE (Object.)
payload (clojure.lang.Box. NONE)
the-e (Exception.)]
(try
(thunk (fn [ret]
(if (identical? NONE (.val payload))
(do (set! (.val payload) ret)
(throw the-e))
(throw (Exception. "Tried to jump outside extent.")))))
(defn memoize-visble-atom [f]
(let [mem (atom {})]
(with-meta
(fn [& args]
(if-let [e (find @mem args)]
(val e)
(let [ret (apply f args)]
(swap! mem assoc args ret))))
{:memoize-atom mem})))
(import '[java.lang.reflect Field Modifier])
(defn private-fields [obj]
(let [obj-class (class obj)
public (set (.getFields obj-class))
all (seq (.getDeclaredFields obj-class))
fields (->> all
(remove public)
(remove #(Modifier/isStatic
(.getModifiers %))))]