rlm@0
|
1 (ns rlm.clojure-example)
|
rlm@0
|
2
|
rlm@0
|
3 (defn curry
|
rlm@0
|
4 "takes a function with a fixed number of args and modifies
|
rlm@0
|
5 it to that it will be automaticaly curried when called with
|
rlm@0
|
6 less args"
|
rlm@0
|
7 ([num-args f & eval-list]
|
rlm@0
|
8 (if (= num-args (count eval-list))
|
rlm@0
|
9 (apply f eval-list)
|
rlm@0
|
10 (fn [& args]
|
rlm@0
|
11 (apply curry num-args f (concat eval-list args))))))
|
rlm@0
|
12
|
rlm@0
|
13 (defn mix
|
rlm@0
|
14 "Takes any number of mathematically equal functions with
|
rlm@0
|
15 possibly different run-times and returns a function that
|
rlm@0
|
16 runs each in a separate thread, returns the result from
|
rlm@0
|
17 the first thread which finishes, and cancels the other threads."
|
rlm@0
|
18 {:author "Robert McIntyre"}
|
rlm@0
|
19 ([& functions]
|
rlm@0
|
20 (fn [& args]
|
rlm@0
|
21 (let [result (promise)
|
rlm@0
|
22 futures
|
rlm@0
|
23 (doall (for [fun functions]
|
rlm@0
|
24 (future (deliver result (apply fun args)))))
|
rlm@0
|
25 answer @result]
|
rlm@0
|
26 (dorun (map future-cancel futures))
|
rlm@0
|
27 answer))))
|
rlm@0
|
28
|
rlm@0
|
29 (defn memoize*
|
rlm@0
|
30 "Returns a memoized version of a referentially transparent
|
rlm@0
|
31 function. The memoized version of the function keeps a cache of the
|
rlm@0
|
32 mapping from argument to results and, when calls with the same
|
rlm@0
|
33 arguments are repeated often, has higher performance at the expense
|
rlm@0
|
34 of higher memory use."
|
rlm@0
|
35 {:added "1.0"}
|
rlm@0
|
36 [f]
|
rlm@0
|
37 (let [mem (atom {})]
|
rlm@0
|
38 (fn [& args]
|
rlm@0
|
39 (if-let [e (find @mem args)]
|
rlm@0
|
40 (val e)
|
rlm@0
|
41 (let [ret (apply f args)]
|
rlm@0
|
42 (swap! mem assoc args ret)
|
rlm@0
|
43 ret)))))
|
rlm@0
|
44
|
rlm@0
|
45 ;;immutable data structures
|
rlm@0
|
46 (def r {:a :a :b :b})
|
rlm@0
|
47 (def b (assoc r :c :c))
|
rlm@0
|
48
|
rlm@0
|
49 (defn collapse [coll & head]
|
rlm@0
|
50 (if (= (count coll) 0)
|
rlm@0
|
51 (first head)
|
rlm@0
|
52 (let [x (first coll)]
|
rlm@0
|
53 (if (list? x)
|
rlm@0
|
54 (collapse (concat x (rest coll)) (first head))
|
rlm@0
|
55 (collapse (rest coll) (conj (vec (first head)) x))))))
|
rlm@0
|
56 ;;email clojure group about this
|
rlm@0
|
57
|
rlm@0
|
58
|
rlm@0
|
59 (defn collapse* [coll]
|
rlm@0
|
60 (loop [head [] body coll]
|
rlm@0
|
61 (let [x (first body)]
|
rlm@0
|
62 (cond (= (count body) 0) head
|
rlm@0
|
63 (list? x) (recur head (concat x (next body)))
|
rlm@0
|
64 true (recur (conj head x) (next body))))))
|
rlm@0
|
65
|
rlm@0
|
66
|
rlm@0
|
67
|
rlm@0
|
68
|
rlm@0
|
69
|