diff 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
line wrap: on
line diff
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/rlm/clojure_example.clj	Tue Oct 18 00:57:08 2011 -0700
     1.3 @@ -0,0 +1,69 @@
     1.4 +(ns rlm.clojure-example)
     1.5 +
     1.6 +(defn curry
     1.7 +  "takes a function with a fixed number of args and modifies
     1.8 +   it to that it will be automaticaly curried when called with
     1.9 +   less args"
    1.10 +  ([num-args f & eval-list]
    1.11 +     (if (= num-args (count eval-list))
    1.12 +       (apply f eval-list)
    1.13 +       (fn [& args]
    1.14 +	 (apply curry num-args f (concat eval-list args))))))
    1.15 +
    1.16 +(defn mix 
    1.17 +  "Takes any number of mathematically equal functions with
    1.18 +   possibly different run-times and returns a function that
    1.19 +   runs each in a separate thread, returns the result from
    1.20 +   the first thread which finishes, and cancels the other threads."
    1.21 +  {:author "Robert McIntyre"}
    1.22 +  ([& functions]
    1.23 +     (fn [& args]
    1.24 +       (let [result (promise)
    1.25 +	     futures
    1.26 +	     (doall (for [fun functions]
    1.27 +		      (future (deliver result (apply fun args)))))
    1.28 +	     answer @result]
    1.29 +	 (dorun (map future-cancel futures))
    1.30 +	 answer))))
    1.31 +
    1.32 +(defn memoize*
    1.33 +  "Returns a memoized version of a referentially transparent
    1.34 +  function. The memoized version of the function keeps a cache of the
    1.35 +  mapping from argument to results and, when calls with the same
    1.36 +  arguments are repeated often, has higher performance at the expense
    1.37 +  of higher memory use."
    1.38 +  {:added "1.0"}
    1.39 +  [f]
    1.40 +  (let [mem (atom {})]
    1.41 +    (fn [& args]
    1.42 +      (if-let [e (find @mem args)]
    1.43 +        (val e)
    1.44 +        (let [ret (apply f args)]
    1.45 +          (swap! mem assoc args ret)
    1.46 +          ret)))))
    1.47 +
    1.48 +;;immutable data structures
    1.49 +(def r {:a :a :b :b})
    1.50 +(def b (assoc r :c :c))
    1.51 +
    1.52 +(defn collapse [coll & head]
    1.53 +  (if (= (count coll) 0)
    1.54 +    (first head)
    1.55 +    (let [x (first coll)]
    1.56 +      (if (list? x)
    1.57 +	(collapse (concat x (rest coll)) (first head))
    1.58 +	(collapse (rest coll) (conj (vec (first head)) x))))))
    1.59 +;;email clojure group about this
    1.60 +
    1.61 +
    1.62 +(defn collapse* [coll]
    1.63 +  (loop [head [] body coll]
    1.64 +    (let [x (first body)]
    1.65 +      (cond (= (count body) 0) head
    1.66 +	    (list? x) (recur head (concat x (next body)))
    1.67 +	    true      (recur (conj head x) (next body))))))
    1.68 +	
    1.69 +
    1.70 +  
    1.71 +
    1.72 +