Skip to content

Instantly share code, notes, and snippets.

@devrimbaris
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devrimbaris/1686eb292a3f08f77d92 to your computer and use it in GitHub Desktop.
Save devrimbaris/1686eb292a3f08f77d92 to your computer and use it in GitHub Desktop.
Various util functions...
(defn CAPITALIZE [x]
(let [parsed (clojure.string/split x #" ")]
(map
#(reduce str %)
(for [x parsed] (conj
(map #(clojure.string/lower-case %) (rest x))
(clojure.string/upper-case (first x)))))))
;-----------------------------------------------------------
;VERY VERY slow compared to java's shuffle for collections
(defn SHUFFLE [coll]
(loop [c coll a []]
(if (empty? c)
a
(let [n (rand-int (count c))
s1 (subvec c 0 n)
[st] (subvec c n (inc n))
s2 (subvec c (inc n))
]
(recur (reduce conj s1 s2) (conj a st) )))))
;-----------------------------------------------------------
;UPDATE2: maybe this is the best? (no reduce!)
(remove
#(some (fn [a] (= a %1)) s)
x)
;UPDATE: maybe the below functions is more elegant :)
(reduce #(remove (fn [x] (= ( :a x) %2)) %1) c1 c2 )
;ORIGINAL
(defn diff-with-f
"Diff of two collections based on the condition function.
Condition function should take two arguments. The items in col-1 which satisfy the cond-f are removed iteratively."
[col-1 col-2 cond-f]
(loop [c1 col-1 c2 col-2]
(if-let [word (first c2)]
(recur
(remove #(cond-f % word) c1)
(rest c2))
c1)))
;;;EXAMPLE
(def c1 [{:a "foo" :b 5}
{:a "foo2" :b 333}
{:a "foo2" :b 24}
{:a "a1" :b 12}
{:a "a2" :b 100}
{:a "foo2" :b 313}
{:a "deneme" :b 60}])
(def c2 ["foo2" "a1"])
(def nums [42])
;;remove items from c1 where :b key is larger than items in nums
(diff-with-f
c1
nums
(fn [x y] (> (:b x) y)) )
;-> ({:b 5, :a "Asdasd"} {:b 24, :a "deneme"} {:b 12, :a "a1"})
;remove items from c1 where :a keywords are equal to the items in c2
(diff-with-f
c1
c2
(fn [x y] (= (:a x) y)) )
;-----------------------------------------------------
(defn merge-map-collections-on-key
"Merges detail info from second map onto first using the key as the idenfier."
[master detail k]
(for [{word :word} master]
(let [[ p1] (filter #(= (k %) word) master)
[ p2] (filter #(= (k %) word) detail)]
(merge p1 p2)
))
)
;example
(def mm1 [ {:word "deneme" :filename "deneme.jpg"}
{:word "kitchen" :filename "kitchen.jpg"}
{:word "black" :filename "black.jpg"}])
(def mm2 [ {:word "deneme" :mp3-url "http://deneme.mp3"}
{:word "kitchen" :mp3-url "http://kitchen.mp3"}
{:word "black" :mp3-url "http://black.mp3"}])
(merge-map-collections-on-key mm1 mm2 :word)
;-->
;({:filename "deneme.jpg", :word "deneme", :mp3-url "http://deneme.mp3"}
;{:filename "kitchen.jpg", :word "kitchen", :mp3-url "http://kitchen.mp3"}
;{:filename "black.jpg", :word "black", :mp3-url "http://black.mp3"})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment