Reputation: 1819
Is there a better way to do this in Clojure?
(if (coll? coll)
(map my-fn coll)
(my-fn coll)
my-fn
is to be applied to input coll
. coll
can be either singular or a collection.
If I don't check for coll?
, using map
alone would throw an IllegalArgumentException for don't know how to create an ISeq from xxx.
Upvotes: 2
Views: 118
Reputation: 106351
Your code is fine (although I'd rename the variable coll since you don't actually know if it is a collection and this might confuse readers).
However I'd suggest this whole chunk of code looks suspiciously like a code smell - it's taking dynamic typing a bit too far / trying to be a bit too clever in my opinion: in the sense of "cleverness considered harmful".
Alternative ideas to consider:
Upvotes: 4
Reputation: 91897
No general solution can exist, because my-fn
may be a function that takes lists and returns lists. Then you can't somehow inspect the input and decide whether to map over it or not.
Better is to not get yourself into the scenario where you don't know what type of data you have, but I can't give any specific advice on this without knowing more about your program.
Upvotes: 1
Reputation: 13514
If coll
doesn't contain any nested sequences:
(map my-fn (flatten (list coll)))
Upvotes: 1