weavejester / medley

A lightweight library of useful Clojure functions
Eclipse Public License 1.0
865 stars 66 forks source link

Higher order functions #7

Closed jarohen closed 10 years ago

jarohen commented 10 years ago

Hi James,

Here's a few additions to Medley that I find myself either wishing for on a regular basis, or duplicating in a number of projects!

all and any are two macros that take in a list of predicates and return another predicate that returns true if all/any of the passed predicates return true - useful for passing to filter/remove.

->% and ->>% are maybe a bit more obscure - they're mostly to get around the restriction that you can't nest anonymous functions (of the #(...) variety) - e.g. :

;; ->% is good for seqs of maps
(let [table [{:a 1 :b [4 12]},
             {:a 3 :b [8 35]}]]
  (map (->% (update-in [:b] #(map inc %))
            (assoc :c 8))
       table))

;; -> [{:a 1, :b [5 13], :c 8},
;;     {:a 3, :b [9 36], :c 8}]

and

;; ->>%, on the other hand, is better for nested seqs
(let [results [[3 5 8 12], [6 45 23 18]]]
  (map (->>% (filter #(zero? (mod % 3)))
             (map #(* 2 %)))
       results))

;; -> [[6 24], [12 90 36]]

I'm happy to change anything about the PR - names/docstrings/implementations - feedback welcome! Also, if you don't feel they belong in Medley, let me know and I'll release them separately.

Thanks for writing and maintaining Medley btw - we use it in a lot of projects at Likely, especially the map-keys and map-vals functions (which seem to turn up in almost every other namespace!).

Hope you're keeping well,

James

jarohen commented 10 years ago

Just spotted these aren't based on master - will re-base

jarohen commented 10 years ago

Just spotted the Travis build - will put my tests in the test suite as well

jarohen commented 10 years ago

(cc @lsnape)

weavejester commented 10 years ago

The any and all macros replicate functionality already available in Clojure. Unless I've misread the code, the some-fn and every-pred functions in clojure.core should provide the same functionality, with the advantage that they're functions, rather than macros.

I can see why the ->% and ->>% macros might be useful, but I'd rather limit Medley to pure functions.

Other than that, I'm glad you're finding Medley useful!

jarohen commented 10 years ago

Thanks for pointing me in the direction of every-pred and some-fn - thought I knew core reasonably well but haven't ever come across those. Also, no worries about the arrows, that's fair enough!

Cheers,

James