有条件地添加到集合中(Conditionally adding to a collection)

编程入门 行业动态 更新时间:2024-10-26 08:29:28
有条件地添加到集合中(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")))

更多推荐

本文发布于:2023-07-15 05:27:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1110681.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有条件   Conditionally   collection   adding

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!