clojureclojure-contrib

Create a list from a string in Clojure


I'm looking to create a list of characters using a string as my source. I did a bit of googling and came up with nothing so then I wrote a function that did what I wanted:

(defn list-from-string [char-string]
  (loop [source char-string result ()]
    (def result-char (string/take 1 source))
    (cond
     (empty? source) result
     :else (recur (string/drop 1 source) (conj result result-char)))))

But looking at this makes me feel like I must be missing a trick.

  1. Is there a core or contrib function that does this for me? Surely I'm just being dumb right?
  2. If not is there a way to improve this code?
  3. Would the same thing work for numbers too?

Solution

  • You can just use seq function to do this:

    user=> (seq "aaa")
    (\a \a \a)
    

    for numbers you can use "dumb" solution, something like:

    user=> (map (fn [^Character c] (Character/digit c 10)) (str 12345))
    (1 2 3 4 5)
    

    P.S. strings in clojure are 'seq'able, so you can use them as source for any sequence processing functions - map, for, ...