Clojure:反转包含的参数?用于 condp
Clojure: Reversing the parameters of contains? for use in condp
我今天发现了这个 clojure 问题:
(condp contains? some-set
"foo" "foo's in thar"
"bar" "bar's in thar"
"t'aint thar")
想法是 return 第一个匹配项下的字符串,其中 some-set
包含一个值。如果 none 个值在集合中,则 return 是最后一个值。问题是,contains?
函数首先获取集合然后是密钥,而 condp
首先需要密钥。
我"fixed"它通过写一个函数:
(defn reverse-params [f] (fn [a b] (f b a))
并替换为对它的调用:
(condp (reverse-params contains?) some-set
"foo" "foo's in thar"
"bar" "bar's in thar"
"t'aint thar")
哪个有效,但我的问题是我是否缺少更好的方法(也许通过使用 some
)?我可以使用 cond
,但我认为这种方式可以节省我一些打字时间。
不,你没有遗漏什么。这是一种正常的处理方式。
如果只使用一次,我经常为此使用匿名函数。
(condp #(contains? %2 %1) some-set
"foo" "foo's in thar"
"bar" "bar's in thar"
"t'aint thar")
使用 ->
和 ->>
宏进行线程处理时也会出现此问题。在这些情况下,我会经常使用 as->
宏来为线程值命名
我今天发现了这个 clojure 问题:
(condp contains? some-set
"foo" "foo's in thar"
"bar" "bar's in thar"
"t'aint thar")
想法是 return 第一个匹配项下的字符串,其中 some-set
包含一个值。如果 none 个值在集合中,则 return 是最后一个值。问题是,contains?
函数首先获取集合然后是密钥,而 condp
首先需要密钥。
我"fixed"它通过写一个函数:
(defn reverse-params [f] (fn [a b] (f b a))
并替换为对它的调用:
(condp (reverse-params contains?) some-set
"foo" "foo's in thar"
"bar" "bar's in thar"
"t'aint thar")
哪个有效,但我的问题是我是否缺少更好的方法(也许通过使用 some
)?我可以使用 cond
,但我认为这种方式可以节省我一些打字时间。
不,你没有遗漏什么。这是一种正常的处理方式。 如果只使用一次,我经常为此使用匿名函数。
(condp #(contains? %2 %1) some-set
"foo" "foo's in thar"
"bar" "bar's in thar"
"t'aint thar")
使用 ->
和 ->>
宏进行线程处理时也会出现此问题。在这些情况下,我会经常使用 as->
宏来为线程值命名