yegor256
yegor256

Reputation: 105073

how to build a hash-set with an element or without it (depending on condition)?

I'm trying this:

(hash-set (when (= a 1) x))

I'm expecting #{x} if a equals to 1 and an empty set #{} otherwise. But I'm getting #{nil} instead of any empty set. How to re-write the statement?

ps. A workaround, but it looks ugly:

(filter #(not (nil? %)) (hash-set (when (= a 1) x)))

The solution:

(apply hash-set (when (= a 1) (list x)))

Upvotes: 1

Views: 196

Answers (3)

Michiel Borkent
Michiel Borkent

Reputation: 34820

Another way:

(into #{} (when (= a 1) [x]))

If you like the word hash-set in your code, you can do:

(apply hash-set (when (= a 1) [x]))

Upvotes: 1

Maurits Rijk
Maurits Rijk

Reputation: 9985

You could use:

(apply hash-set (when (= a 1) x))

I'm assuming that a and x are variables, for example via:

(defn foo [a & x] (apply hash-set (when (= a 1) x)))

I made the parameter x optional since you don't need to provide it if a not equals 1.

Upvotes: 1

user100464
user100464

Reputation: 18429

You could do:

(if (= a 1) #{x} #{})

Upvotes: 0

Related Questions