Skip to content

Instantly share code, notes, and snippets.

(defn repeat
([x] (iterate identity x))
([n x] (take n (repeat x))))
(def bar (doall (repeat 100 5)))
(defn mapmap [f coll]
(zipmap coll (map f coll)))
;; => (time (dotimes [_ 10000] (mapmap (partial * 10) bar)))
(defmacro with-out-str
[& body]
`(let [s# (new java.io.StringWriter)]
(binding [*out* s#]
(let [result# (do ~@body)]
[(str s#) result#]))))
(defmacro with-out-str
[& body]
`(let [s# (new java.io.StringWriter)]
(defn partialr [f & r-args]
(fn [& l-args] (apply f (concat l-args r-args))))
(deftype Foo []
clojure.lang.IFn
(invoke [_] (+ 1 2)))
((Foo.))
;; => 3
(defmacro do-when
{:arglists '([test then & more])}
[& clauses]
(if-not (even? (count clauses))
(throw (IllegalArgumentException. "do-when requires an even number of clauses."))
(cons 'do (map (partial cons 'when)
(partition 2 clauses)))))
(...
`(do (defnk ~fn-name ~@fn-tail)
(alter-meta! (var ~fn-name) assoc :arglists ~arglists)
(var ~fn-name)))
(defmacro defunk [fn-name & fn-tail]
(let [arglists (some :arglists fn-tail)]
`(do (defnk ~fn-name ~@fn-tail)
(when ~arglists (alter-meta! (var ~fn-name) assoc :arglists ~arglists))
(var ~fn-name))))
(use 'clojure.walk)
(defmacro ->_
"Threads the forms, replacing underscores with the result of the last expression."
([x] x)
([x form] (if (seq? form)
(with-meta (postwalk-replace {'_ x} form) (meta form))
(list form x)))
([x form & more] `(->_ (->_ ~x ~form) ~@more)))
(defmacro defcommand
{:arglists '([command docstring? attr-map? args & fn-tail])}
[command & fn-tail]
(let [[command [args & body]] (name-with-attributes command fn-tail)]
`(do (defn ~command ~@fn-tail)
(meta (var ~command)))))
(comment
(ns clj-chat.core
(defn some-name [f] ;; Takes a function that
(fn [& fns] ;; Returns a function that takes a list of functions that returns
(fn [& args] ;; A function that calls the original function with identity over applying each function to the args of this anonymous function #ohgod
(f identity (map apply fns (repeat args))))))
;;; All Kinds of Destructuring ;;;
(let [foo 1] foo)
; => 1
(let [[foo bar] [1 2 3]] [foo bar])
; => [1 2]
(let [[foo bar & baz] [1 2 3]] [foo bar baz])
; => [1 2 (3)]