Clojure:反转包含的参数?用于condp

sta*_*and 6 clojure

我今天发现了这个clojure问题:

(condp contains? some-set
   "foo"   "foo's in thar"
   "bar"   "bar's in thar"
   "t'aint thar")
Run Code Online (Sandbox Code Playgroud)

我们的想法是在some-set包含值的第一个匹配项下返回字符串.如果集合中没有值,则返回最后一个值.问题是,contains?函数首先采集集合然后是密钥并condp首先需要密钥.

我通过写一个函数"修复"它:

(defn reverse-params [f] (fn [a b] (f b a))
Run Code Online (Sandbox Code Playgroud)

并用一个电话代替它:

(condp (reverse-params contains?) some-set
   "foo"   "foo's in thar"
   "bar"   "bar's in thar"
   "t'aint thar")
Run Code Online (Sandbox Code Playgroud)

哪个有效,但我的问题是我错过了一些更好的方法(也许通过使用some)?我可以使用,cond但我想这样可以节省一些打字.

Art*_*ldt 10

不,你不会错过任何东西.这是一种正常的方式.如果它只使用一次,我经常使用匿名函数.

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

使用->->>宏线程化时,也会出现此问题.在这些情况下,我经常使用as->宏来为线程值赋予名称