Skip to content

Instantly share code, notes, and snippets.

@amalloy
amalloy / gist:848084
Created February 28, 2011 21:36 — forked from ray1729/gist:848069
;; not sure whether this is an improvement but I don't really like letfn
(defn keep-only
[n bucket-fn s]
((fn my-filter
[s seen]
(lazy-seq
(when (seq s)
(let [e (first s)
b (bucket-fn e)
c (inc (get seen b 0))]
(use 'name.choi.joshua.fnparse)
(def tokenize (partial re-seq #"[\[\](){}]|[^\[\](){}]+"))
(defn initial-state
[input] {:remainder (tokenize input)
:brackets (list)})
@amalloy
amalloy / core.clj
Created March 23, 2011 18:21 — forked from Raynes/core.clj
(import java.awt.event.ActionListener)
(defn add-action [cmp fn]
(doto cmp
(.addActionListener (doto (proxy [ActionListener] [])
(update-proxy {"actionPerformed" fn})))))
(defn add-action [cmp fn]
(doto cmp
(.addActionListener (reify ActionListener
(defmacro when-lets [bindings & body]
(reduce (fn [acc tstform]
`(when-let ~tstform ~acc))
(cons 'do body)
(reverse (map vec (partition 2 bindings)))))
(when-lets [n (first sizes)
s (seq coll)]
(cons (take n coll)
(partitions (next sizes) (drop n coll)))))
(defmacro phase-fn
([argvec] identity)
([argvec subphase & left]
`(fn [session# ~@argvec]
(--> session#
~subphase
~@(when left
[`((phase-fn ~argvec ~@left))])))))
(defmacro defratios
"Defines two converter functions with num-expr being how many of a make up b.
For example, there are 100 centimeters in a meter. To tell the program to make
(centimeter->meter) and (meter->centimeter), use (defratios meter centimeters 100)"
[a-symb b-symb num-expr]
(and (every? #{clojure.lang.Symbol}
(map type [a-symb b-symb]))
(let [ab-symb (symbol (arr a-symb b-symb))
ba-symb (symbol (arr b-symb a-symb))
num (gensym "num-")]
(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)
@amalloy
amalloy / function-keyword.clj
Created June 14, 2011 17:40 — forked from halfprogrammer/function-keyword.clj
Keywords as function parameters in clojure?
(defn my-exists1? [lst obj & {:keys [testfn] :or {testfn =}}]
(loop [lst lst, obj obj]
(when lst
(if (testfn (first lst) obj)
lst
(recur (next lst) obj)))))
(my-exists1? '((1 2) (3 4) (5 6)) 3 :testfn #(= (first %1) %2))
@amalloy
amalloy / gist:1047993
Created June 26, 2011 21:35 — forked from kiras/gist:1047989
Sierpinski Gasket code
(defn sierpinskisize
"Chooses a vertex from tri at random, returning the point halfway between
p and the vertex."
[p tri]
(let [v-num (rand-int 3)
vertex ((case v-num
0 :p1
1 :p2
2 :p3) tri)
halfway-point (fn [p1 p2]
@amalloy
amalloy / gist:1074857
Created July 10, 2011 19:12 — forked from swannodette/gist:1074818
change.clj
(def denoms [1000 500 100 25 5 1])
(def names {2000 :twenties
1000 :tens
500 :fives
100 :dollars
25 :quarters
5 :nickels
1 :pennies})