Share your thoughts in the 2024 State of Clojure Survey!

Welcome! Please see the About page for a little more info on how this works.

+1 vote
in Clojure by

I'm trying to use the join function to group some strings in a singular string but I'd like to avoid empty strings.

For example, if I try to join ["" "" "xpto"] the return is "--xpto" and actually I think is weird and I'd like to avoid it.

To do it I created a util function removing it

(defn join-not-empty
  [separator coll]
  (join separator (remove empty? coll)))

I'd like if make sense to use this approach as an option in the join function.

1 Answer

+3 votes
by
selected by
 
Best answer

I have run into stuff like this a number of times so I feel your pain and wouldn't be against additional options.

However, this sounds like a user-space problem to me. Why empty? and not str/blank?, what about other predicates or even ones that look at pairs of elements etc.

One could consider join as an aggregation, with (remove empty?) and coll as its inputs and could arrive at a great use for transducers. In fact, Chris Grand's xforms already has a suitable transducing context that could be used for this: x/str

Wrapping this beauty gives you:

(require '[net.cgrand.xforms :as x])
(defn str-join
  "Works like a combination of str/join and x/str:
  - Use str/join if you don't need to preprocess coll
  - Use x/str if you need to preprocess coll but don't need a separator
  - Use this function if you need both preprocessing and a separator"
  [xform separator coll]
  (x/str (comp xform (interpose separator)) coll))
by
The reason to use the empty? is only to illustrate the problem. I liked this x/str approach.
...