How to split a number in Clojure?

You could simply do

(map #(Character/digit % 10) (str 942))

EDIT: Adding a function definition

(defn digits [number] (map #(Character/digit % 10) (str number)))

Usage:

(digits 1234)

Note: This is concise, but does use java String and Character classes. An efficient implementation can be written using integer modulo arithmetic, but won't be concise. One such solution similar to Charles' answer would be:

(defn numTodigits
  [num]
  (loop [n num res []]
    (if (zero? n)
      res
      (recur (quot n 10) (cons (mod n 10) res)))))

Source


I'm not sure about concise, but this one avoids unnecessary inefficiency such as converting to strings and back to integers.

(defn digits [n]
  (loop [result (list), n n]
    (if (pos? n)
      (recur (conj result (rem n 10))
             (quot n 10))
      result)))

A concise version of your first method is

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

... and of your 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 is essentially eager, since the last digit in is the first out. So we might as well use mapv and rseq (instead of map and reverse) to do it faster.
  • The function is transducer-ready.
  • It works properly only on positive numbers.

Tags:

Clojure