How to split a number in Clojure? -


i looking nice method split number n digits in clojure have these 2 verbose inefficient methods:

 (->> (str 942)       seq       (map str)       (map read-string)) => (9 4 2) 

and...

(defn digits [n] ;yuk!!    (cons        (str (mod n 10)) (lazy-seq (positive-numbers (quot n 10)))))  (map read-string (reverse (take 5 (digits 10012)))) => (1 0 0 1 2) 

is there more concise method doing type sort of operation?

a concise version of first method is

(defn digits [n]   (->> n str (map (comp read-string str)))) 

... , of second is

(defn digits [n]   (if (pos? n)     (conj (digits (quot n 10)) (mod n 10) )     [])) 

an idiomatic alternative

(defn digits [n]   (->> n        (iterate #(quot % 10))        (take-while pos?)        (mapv #(mod % 10))        rseq)) 

for example,

(map digits [0 942 -3]) ;(nil (9 4 2) nil) 
  • the computation eager, since last digit in first out. might use mapv , rseq (instead of map , reverse) faster.
  • the function transducer-ready.
  • it works on positive numbers.

Comments