Viktor K.
Viktor K.

Reputation: 2740

Create function by making argument of another function constant (clojure,newbie)

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?

Upvotes: 1

Views: 96

Answers (1)

Óscar López
Óscar López

Reputation: 236150

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?))

Upvotes: 7

Related Questions