stand
stand

Reputation: 3132

Clojure: Reversing the parameters of contains? for use in condp

I discovered this clojure problem today:

(condp contains? some-set
   "foo"   "foo's in thar"
   "bar"   "bar's in thar"
   "t'aint thar")

The idea is to return the string under the first match where some-set contains a value. If none of the values is in the set, it returns the last value. Problem is, the contains? function takes the collection first then the key and condp needs the key first.

I "fixed" it by writing a function:

(defn reverse-params [f] (fn [a b] (f b a))

and substituting a call to it:

(condp (reverse-params contains?) some-set
   "foo"   "foo's in thar"
   "bar"   "bar's in thar"
   "t'aint thar")

Which works, but my question is am I missing some better way to do this (maybe by using some)? I could use cond but I figured this way saves me some typing.

Upvotes: 8

Views: 484

Answers (1)

Arthur Ulfeldt
Arthur Ulfeldt

Reputation: 91554

Nope, you're not missing something. This is a normal way of going about it. I often use an anonymous function for this if it will only be used once.

(condp #(contains? %2 %1) some-set
   "foo"   "foo's in thar"
   "bar"   "bar's in thar"
   "t'aint thar")

This problem also comes up when threading things with the -> and ->> macros. In those cases I'll often use the as-> macro to give the threaded value a name

Upvotes: 14

Related Questions