Skip to content

Instantly share code, notes, and snippets.

@edw
Created January 31, 2011 15:18
Show Gist options
  • Select an option

  • Save edw/804165 to your computer and use it in GitHub Desktop.

Select an option

Save edw/804165 to your computer and use it in GitHub Desktop.
Sequence operations that operate on a subset of values of each sequence element.
(defn- make-getter [indices]
(let [indices (if (sequential? indices) indices [indices])]
(fn [coll] (map #(nth coll %) indices))))
(defn map* [indices proc coll]
(let [getter (make-getter indices)]
(map #(apply proc (getter %)) coll)))
(defn filter* [indices pred? coll]
(let [getter (make-getter indices)]
(filter #(apply pred? (getter %)) coll)))
(defn reduce*
([indices proc seed coll]
(let [getter (make-getter indices)]
(reduce #(apply proc (getter %)) seed coll)))
([indices proc coll]
(let [getter (make-getter indices)]
(reduce #(apply proc (getter %)) coll))))
(defn sort* [indices comp coll]
(let [getter (make-getter indices)
multi-indices? (and (sequential? indices) (> (count indices) 1))
atom-or-sequence (fn [vs] (if multi-indices? vs (first vs)))]
(sort #(comp (atom-or-sequence (getter %)) (atom-or-sequence (getter %2))) coll)))
(defn group-by* [indices coll]
(let [getter (make-getter indices)
multi-indices? (and (sequential? indices) (> (count indices) 1))
atom-or-sequence (fn [vs] (if multi-indices? vs (first vs)))]
(reduce (fn [newcoll v]
(let [k (atom-or-sequence (getter v))
group (get newcoll k [])]
(assoc newcoll k (conj group v))))
{}
coll)))
(defn nth* [indices coll]
(let [getter (make-getter indices)
multi-indices? (and (sequential? indices) (> (count indices) 1))
atom-or-sequence (fn [vs] (if multi-indices? vs (first vs)))]
(map #(atom-or-sequence (getter %)) coll)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment