Skip to content

Instantly share code, notes, and snippets.

(defn seqable? [x]
(or (instance? clojure.lang.ISeq x)
(instance? clojure.lang.Seqable x)
(instance? Iterable x)
(instance? CharSequence x)
(instance? java.util.Map x)
(nil? x)
(.. x getClass isArray)))
(def *multi-value* false)
(defmacro with-values [vars expr body]
`(binding [*multi-value* true]
(let [[~@vars] ~expr]
~body)))
(defn values [& vals]
(if *multi-value*
vals
;; clojure.contrib.lazy-seqs/primes
(defn primes
([] (cons 2 (primes [2] 3)))
([ps n]
(lazy-seq
(if (not-any? #(zero? (rem n %)) (take-while #(<= (* % %) n) ps))
(cons n (primes (conj ps n) (+ 2 n)))
(primes ps (+ 2 n))))))
(defn reduce-to [n coll]
(lazy-loop [[f & r :as s] (rest coll)
c (first coll)]
(if f
(if (< c n)
(lazy-recur r (+ c f))
(cons c (reduce-to n s)))
(when c [c]))))
(defn reduce-to [n coll]
(defn form-generate [division-coll callee]
(for [division division-coll
:let [dtype (:dtype division)
args (:args division)]]
;; division can be repeatable, so here we need a loop
;; + each division name and loop index should be carried down
;; to the question tail
(dtype-get dtype callee
(if (= dtype :question)
args
(defn routes
"Calculates all the routes from [x y] to [0 0].
Routes move only down and left."
[x y]
((fn routes* [queue]
(lazy-seq
(loop [queue queue]
(when (pos? (count queue))
(let [[current-level [x y]] (peek queue)
queue-left (pop queue)
(defmacro nested-for
"Like clojure.core/for but returns a nested structure for each sequence.
(for [x [:a :b] y (range 5) :when (odd? y)] [x y])
;=> (([:a 1] [:a 3]) ([:b 1] [:b 3]))"
[seqs body]
(let [groups (reduce (fn [groups [k v]]
(if (keyword? k)
(conj (pop groups) (into (peek groups) [k v]))
(conj groups [k v])))
@mecdemort
mecdemort / map-keys.clj
Created March 31, 2011 21:20
If a map contains a key, do something
(cond
(:key1 m) key1
(:key2 m) key2
(:key3 m) key3
:else nokey)
(condp apply [m]
:key1 key1
:key2 key2
:ley3 key3
@mecdemort
mecdemort / walk.clj
Created March 31, 2011 04:17
mec.walk
(ns mec.walk)
(defn f-walk [inner outer form]
(outer
(if (coll? form)
(into (empty form) (map inner form))
form)))
(defn f-postwalk
"Depth first post-order traversal of form, apply successive fs at each level.
(defmacro when-lets [bindings & body]
(let [[form tst & rest] bindings]
(if (seq rest)
`(when-let [~form ~tst] (when-lets ~rest ~@body))
`(when-let [~form ~tst] ~@body))))
(defmacro when-lets [bindings & body]
(reduce (fn [acc formtst]
`(when-let ~(vec formtst) ~acc))
(cons 'do body)