Paul Lam
Paul Lam

Reputation: 1819

Map to accept singular or collection

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

Answers (3)

mikera
mikera

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:

  • If you actually want to treat everything like a collection, then wrap singular input values when they are first obtained in a list/vector of length 1. Then the rest of your code can safely assume collections throughout.
  • Write separate functions to deal with collections and single values. The rationale is that they are conceptually different data types, so deserve different treatment.

Upvotes: 4

amalloy
amalloy

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

skuro
skuro

Reputation: 13514

If coll doesn't contain any nested sequences:

(map my-fn (flatten (list coll)))

Upvotes: 1

Related Questions