有条件地添加到集合中(Conditionally adding to a collection)
我想根据条件向集合中添加一些东西,否则就不管它了。
我发现自己写的是这样的:
(defn make-zoo [zoo has-ice] (let [zoo (if has-ice (conj zoo "penguins") zoo)] zoo)) (make-zoo ["tigers"] false) ;["tigers"] (make-zoo ["polar bears"] true) ;["polar bears" "penguins"]我对Clojure很陌生,但对于常见的操作来说,这似乎是一个笨重的解决方案。 有更优雅的方式来解决这个问题吗?
I want to add something to a collection based on a condition and leave it alone otherwise.
I found myself writing something like this:
(defn make-zoo [zoo has-ice] (let [zoo (if has-ice (conj zoo "penguins") zoo)] zoo)) (make-zoo ["tigers"] false) ;["tigers"] (make-zoo ["polar bears"] true) ;["polar bears" "penguins"]I'm pretty new to Clojure, but this seems like a clunky solution for a common operation. Is there a more elegant way to address this?
最满意答案
我们可以使用cond-> macro来简化make-zoo ,它是->线程宏的条件派生词:
(defn make-zoo [zoo has-ice] (cond-> zoo, has-ice (conj "penguins")))We can simplify make-zoo using the cond-> macro, a conditional derivative of the -> threading macro:
(defn make-zoo [zoo has-ice] (cond-> zoo, has-ice (conj "penguins")))
更多推荐
发布评论