Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

clojure

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.

like image 989
stand Avatar asked Jan 16 '15 00:01

stand


1 Answers

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

like image 120
Arthur Ulfeldt Avatar answered Oct 19 '22 20:10

Arthur Ulfeldt