view mtg/frame.clj @ 3:44d3dc936f6a

moved backup files
author Robert McIntyre <rlm@mit.edu>
date Fri, 28 Oct 2011 00:06:37 -0700
parents b4de894a1e2e
children
line wrap: on
line source
1 (ns mtg.frame)
3 ;; GENERALLY USEFUL FUNCTIONS
5 (defn assay "Takes x and a series of pred-value pairs. Returns a list of vals for which the corresponding preds are true of x." [x & pred-vals]
6 (reduce #(if ((first %2) x) (conj %1 (second %2))) '() pred-vals)
7 )
8 (defn alter-val "Applies f to the current value associated with each key, associating each key with the value returned." [m f & keys]
9 (map #(assoc m % (f (get m %))) keys))
11 (defn every-nth "Returns every nth member of coll. If n is not positive, returns an empty list." [n coll]
12 (if (<= n 0) '()
13 (take-while (comp not nil?) (map first (iterate #(nthnext % n) coll)))))
19 ;; FRAME MANIPULATION
21 (defn conj-key "Adds the xs to the seq associated with the given key." [map key & xs]
22 (assoc map key (apply conj (get map key []) xs)))
24 (defn update "Takes a frame and a sequence of key-fn pairs. Applies f to the current value associated with key, updating the current value with the result. Frames generate and store a unique id for each call to update."
25 [frame & kfs]
26 (let [id (gensym "")
27 keys (every-nth 2 kfs)
28 fns (every-nth 2 (rest kfs))]
30 ((reduce comp (map (fn[k f](fn[m](conj-key m k (list id f)))) keys fns))
31 (conj-key frame :*bindings* (map (fn [k f](list id k)) keys fns))
32 )
33 ))
35 (defn rollback "Undo the update with the given id." [frame id]
36 (let [affected-keys
37 (conj (map second (filter #(=(first %) id) (:*bindings* frame))) :*bindings*)]
38 (reduce (fn[frame key]
39 (alter-val (partial filter #(=(first %) id)) key)
40 ) frame affected-keys)
41 ))
44 (defn get-fn "Keys in a frame store lists of modifiers. Produces the end result of applying all the modifiers in order." [frame key]
45 (reduce #(%2) (constantly nil) (list (constantly 1)))
46 )
49 (def *frame* (atom {:*bindings* '()}))