Search code examples
clojure

When I map a list in Clojure, how can I intersperse it with other text?


Imagine I have a list like

(def nodes ["a", "b", "c"])

I want to transform nodes into the following string:

a -> b -> c

How can I do it?

(apply str (mapcat
             (fn [node]
               (str node " -> ")
               )
             nodes
             )
       )

results in

"a -> b -> c -> "

I could now check whether or not the resulting string ends with -> and if it does, remove the last ->.

But this does not seem very elegant. What is the right way to do this in Clojure?

Update 1:

(transduce
  (fn [rf]
    (fn
      ([] "")
      ([result] result)
      ([result input] (str
                        result
                        "->"
                        input))
      )
    )
   cat
   ""
   nodes
  )

results in

"->a->b->c"


Solution

  • (def nodes ["a" "b" "c"])
    
    (clojure.string/join " -> " nodes) ;; => "a -> b -> c"