Attilio
Attilio

Reputation: 1722

Clojure: built-in or one-line solution to insert nil into a collection

Consider the following function call: (into [] (some_expression))

Let's say that (some_expression) may either yield nil, or some valid vector (e.g. [1 2 3]). What I would like to achieve is, that if the result of (some_expression) is nil, then I end up with [nil], instead of [] (after executing into). (Of course, if it is some valid vector, like [1 2 3], then I would like to have [1 2 3].)

Possibilities I've considered so far:

I'm afraid there is no short solution, because otherwise it would have been mentioned in that question; still that one is quite old, so I'm hoping maybe they added that feature to Clojure since then.

Also, there are some key differences with that question:

Upvotes: 2

Views: 115

Answers (1)

Nick
Nick

Reputation: 8530

or allows you to specify a fallback of [nil] if some-expression yields nil or false:

(into [] (or (some-expression) [nil]))

Upvotes: 4

Related Questions