On Feb 17, 11:39 am, Shantanu Kumar <kumar.shant...@gmail.com> wrote: > On Feb 17, 11:09 am, Ken Wesson <kwess...@gmail.com> wrote: > > > > > > > > > > > On Thu, Feb 17, 2011 at 12:29 AM, Andreas Kostler > > > <andreas.koestler.le...@gmail.com> wrote: > > > Is there an easy and idiomatic way of getting the digits of a number in > > > clojure? > > > > (defn explode-to-digits [number] > > > (map #(- (int %) (int \0)) (str number))) > > > (explode-to-digits 123456) > > > => (1 2 3 4 5 6) > > > > Seems a bit clunky... > > > How about > > > (defn explode-to-digits [n] > > (if (= n 0) > > [] > > (let [d (rem n 10) > > r (quot n 10)] > > (conj (explode-to-digits r) d)))) > > > or if you want to avoid consuming stack > > > (defn explode-to-digits* [n out] > > (if (= n 0) > > out > > (let [d (rem n 10) > > r (quot n 10)] > > (recur r (cons d out))))) > > > (defn explode-to-digits [n] > > (explode-to-digits* n nil)) > > > It should also be possible to make a lazy sequence version, but > > returning the digits in the reverse order. > > A bit shorter: > > (defn digits [n] > (let [r (rem n 10) > q (int (/ n 10)) > _ (println (format "q=%d, r=%d" q r))] > (if (zero? q) [r] > (into [r] (digits q))))) > > Not efficient though.
Oops, the earlier version that uses conj is shorter indeed. Cheers, Shantanu -- You received this message because you are subscribed to the Google Groups "Clojure" group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en