Last active
March 31, 2016 14:40
-
-
Save whamtet/4a2e1c471b65b0501634 to your computer and use it in GitHub Desktop.
Clojure Gems
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns gems) | |
(def unique-by | |
"inverts the range of f" | |
[f s] | |
(vals (zipmap (map f s) s))) | |
(defn decompose-map | |
"nested map structure -> list of 'address vectors'" | |
([m] (decompose-map [] m)) | |
([stack m] | |
(if (map? m) | |
(mapcat | |
(fn [[k v]] | |
(decompose-map (conj stack k) v)) m) | |
[(conj stack m)]))) | |
(defn recompose-map | |
"list of 'address vectors' -> nested map structure" | |
([vs] (reduce-map {} vs)) | |
([m vs] | |
(reduce | |
(fn [m v] | |
(assoc-in m (pop v) (peek v))) m vs))) | |
;now we can permute nested structures!!! | |
(defn permute-map [m permutation] | |
(recompose-map | |
(map #(mapv % permutation) (decompose-map m)))) | |
(defn max-by | |
"finds an element of s that maximizes f" | |
[f [head & rest]] | |
(if head | |
(first | |
(reduce (fn [[x y] xd] | |
(let [yd (f xd)] | |
(if (< y yd) | |
[xd yd] | |
[x y]))) [head (f head)] rest)))) | |
(defn cumul | |
"cumulation of a sequence" | |
[s] | |
(reduce (fn [a b] (conj a (+ (peek a) b))) [(first s)] (rest s))) | |
(defn diff | |
"difference of items in a sequence" | |
[s] | |
(map - (drop 1 s) s)) | |
;auxiliary function | |
(defn interpose-spaces [s] | |
(apply str (interpose " " s))) | |
(defn xml | |
"A DSL to generate xml" | |
[x] | |
(cond | |
(vector? x) | |
(let [ | |
[tag m & rest] x | |
] | |
(if (map? m) | |
(format "<%s %s>%s</%s>" | |
(name tag) | |
(interpose-spaces (map (fn [[k v]] (format "%s = \"%s\"" k v)) m)) | |
(interpose-spaces (map xml rest)) | |
(name tag)) | |
(format "<%s>%s</%s>" | |
(name tag) | |
(interpose-spaces (map xml (conj rest m))) | |
(name tag)))) | |
:default | |
x)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment