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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With