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