For example, let's say I have a list
'("The" " " "Brown" " " "Cow")
I want to turn this into
"The Brown Cow"
Is there a command in clojure that does this?
I would rather use apply for that:
(apply str '("The" " " "Brown" " " "Cow"))
Since it calls the function just once, it is much more efficient for large collections:
(defn join-reduce [strings] (reduce str strings))
(defn join-apply [strings] (apply str strings))
user> (time (do (join-reduce (repeat 50000 "hello"))
nil))
"Elapsed time: 4708.637673 msecs"
nil
user> (time (do (join-apply (repeat 50000 "hello"))
nil))
"Elapsed time: 2.281443 msecs"
nil
str requires only one StringBuilder instance.As Chris mentioned you can just use clojure.string/join
another way without using a library (assuming you don't want any spaces.) is:
(reduce str '("The" " " "Brown" " " "Cow"))
will return
"The Brown Cow"
str takes a list of things and turns them into one string. You can even do this: (str "this is a message with numbers " 2 " inside")
(apply str coll) better? since it calls the str function just once, while reduce does it (dec (count coll)) times.reduce str on a sequence.Please, people, just say 'No' to the lists! So simple with vectors:
(ns clj.demo
(:require [clojure.string :as str] ))
(def xx [ "The" " " "Brown" " " "Cow" ] )
(prn (str/join xx))
;=> "The Brown Cow"
Quoted lists like:
'( "The" " " "Brown" " " "Cow" )
are much harder to type and read, and also more error-prone than a simple vector literal:
[ "The" " " "Brown" " " "Cow" ]
Also cut/paste is much easier, as you don't need to worry about adding the quote or forgetting to add it.
Note that (str/join ... can also accept an optional separator as the first argument. You can either use the 1-char string like the first example or a "literal" as in the 2nd example:
(ns clj.demo
(:require
[clojure.string :as str]
[tupelo.core :as t] ))
(let [words ["The" "Brown" "Cow"]]
(t/spyx (str/join " " words))
(t/spyx (str/join \space words)))
with results
(str/join " " words) => "The Brown Cow"
(str/join \space words) => "The Brown Cow"
clojure.string/join works for any seq. What did you want to say? that using vector is faster here? No, it's not. In fact join is even a bit slower than apply str in this particular case.str/join is a fine solution.
[ "The" " " "Brown" " " "Cow" ]