aaronjkrause
aaronjkrause

Reputation: 849

Conditionally adding to a collection

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?

Upvotes: 1

Views: 435

Answers (2)

Thumbnail
Thumbnail

Reputation: 13473

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")))

Upvotes: 6

Alan Thompson
Alan Thompson

Reputation: 29958

One simplification is to just leave out the let statement:

(defn make-zoo
  [zoo has-ice]
  (if has-ice
    (conj zoo "penguins")
    zoo))

(make-zoo ["tigers"] false) => ["tigers"]
(make-zoo ["polar bears"] true) => ["polar bears" "penguins"]

Upvotes: 3

Related Questions