Reputation: 1722
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:
vec
: wrong, because (vec nil) = []
, thus the end result is still []
vector
: wrong, since (vector [1 2 3]) = [[1 2 3]]
, thus, the end result will be [[1 2 3]]
. (It would work for nil
, though.)ensure-vector
or as-vector
in this related question: that would solve the problem, but I'm asking if there is something shorter (maybe built into Clojure) that achieves the same(into [] (let [result (some_expression)] (if (nil? result) [nil] result)))
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:
ensure-vector
" I'm looking for has to work only for nil
. (I.e., it is fine if (ensure-vector 2)
returns 2
and not [2]
.) I guess this does not really count, but who knows.ensure-vector
" would be fine too. E.g., if into
had some special parameter that caused it to interpret the from
argument as a value to be inserted, instead of the source collection, that would also solve my problem. (This is more for the sake of making an example: as far as I understand the documentation of into, it does not have such form. Although, frankly, I'm not quite sure what xform
means in (into to xform from)
. But I guess it is something else...)Upvotes: 2
Views: 115