albusshin
albusshin

Reputation: 4010

How to convert a function that accept multiple parameters into a predicate?

I see the following code on the Clojure wikibook

user=> (filter nil? [:a :b nil nil :a]) 
(nil nil)

and I see nil? is a predicate. However, I currently want to convert clojure.contrib.string/substring? into a predicate, which means, although substring is a function that accepts two parameters, I want to set the first one as fixed. How can I do that?

Currently I'm doing this by writing something like this

(filter (fn [x] (clojure.contrib.string/substring? "todo" x))
        ["todo" "todo" nil "todos"])

Is there a better way?

Upvotes: 0

Views: 385

Answers (1)

A. Webb
A. Webb

Reputation: 26446

Your code is fine except

  • clojure.contrib.string has been absorbed into clojure.string and substring? is no more. See clojure.contrib migration.

  • You need protection from the nils in your sample data.

You can also use the #() reader macro if you like, for example with regular expressions

(filter #(when % (re-find #"todo" %)) ["todo" "todo" nil "todos"])

or Java interop

(filter #(when % (.contains % "todo")) ["todo" "todo" nil "todos"])

both

;=> ("todo" "todo" "todos")

Upvotes: 7

Related Questions