1

I just started to learn clojure and I don't have much functional programming experience. Let's say I have a function :

(defn process-seq
   [process]
   ...doing something...)

that takes another function as an argument. This argument should be a function that takes single argument - a sequence. For example :

(defn filter-odd
  [sequence]
  (filter odd? sequence))

So I can now write :

(process-seq filter-odd)

What I don't like about it is that I had to define filter-odd function. I would like to achieve it without defining it. All I want is to pass filter function with constant predicate : odd?.Something like (just a pseudo code that I made up) :

(process-seq filter(odd?))

Is something like that possible?

Viktor K.
  • 2,670
  • 2
  • 19
  • 30

1 Answers1

7

You can pass an anonymous function as parameter:

(process-seq (fn [sequence] (filter odd? sequence)))

Or even shorter:

(process-seq #(filter odd? %))

Or as mentioned by A.Webb in the comments, we could use partial:

(process-seq (partial filter odd?))
Community
  • 1
  • 1
Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • 2
    Also `(process-seq (partial filter odd?))` – A. Webb Feb 26 '14 at 03:36
  • 1
    Partial is not currying. – ClojureMostly Feb 26 '14 at 03:48
  • @Aralo looks like currying to me, what's the difference? it's even mentioned in the comments of the [documentation](http://clojuredocs.org/clojure_core/clojure.core/partial) – Óscar López Feb 26 '14 at 03:58
  • `partial` is partial application. Currying would be more like `(filter f)` implicitly "noticing" that too few arguments are passed, and returning a new function that expects a collection. – amalloy Feb 26 '14 at 04:30
  • 2
    Currying would be `(def curried-filter (fn [pred] (fn [coll] (filter pred coll))))`. And in this case, `(partial filter odd?)` would correspond to `(curried-filter odd?)`. – A. Webb Feb 26 '14 at 04:36
  • 1
    See http://stackoverflow.com/questions/218025/what-is-the-difference-between-currying-and-partial-application – ClojureMostly Feb 26 '14 at 13:06