Divide a sequence of numbers in clojure

I have the following input:

(def nums [123456789012 123456789012])

I need the following output:

[[1234 5678 9012] [1234 5678 9012]]

* note that both of these sequences contain non-string numbers ...

I thought it would be very simple by doing the following:

  • Convert each record to string
  • Divide each line by 4
  • Convert each section back to an integer

Here is my unsuccessful attempt:

(defn split-nums [nums factor]
  (map
    #(map
       (fn [x] (Integer/valueOf (str x)))
       (partition factor (str %)))
  nums))

(println (split-nums nums, 4))

When I run this, I get the following error:

Caused by: java.lang.NumberFormatException: For input string: "clojure.lang.LazySeq@4834333c"

Which tells me that I am dealing with the lazy sequence that I need to evaluate, but when I try (str (doall x)), I get the same result.

So clojure experts, where am I mistaken? Is this a good approach? BTW. I just started to learn clojure, so I'm certainly not an expert.

+3
source share
6
(defn split-nums [nums factor]
  (map #(map (fn [x] (Integer/valueOf (apply str x))) ; apply str
             (partition factor (str %)))
       nums))

(str (lazy-seq [1])) ; "clojure.lang.LazySeq@20"

(apply str (lazy-seq [1])) ; "1"


, , , , map , .

(defn split-number [n factor]
  (->> (str n)
       (partition-all factor) ;; or partition
       (map (partial apply str))
       (map #(Integer/valueOf %))))

(map #(split-number % 4) [12345678 12345678]) ;; => ((1234 5678) (1234 5678))


, :

(mod 5151 10) ;; => 1 .

(/ 5151 10) ;; => 515 .

+4

String? / mod. .

(defn int-partition [num size]
   (let [f (int (Math/pow 10 size))]
      (loop [n num l ()]
         (if (zero? n) 
            (vec l) 
            (recur (int (/ n f)) (conj l (mod n f)))))))

(defn split-nums [nums factor] (vec (map #(int-partition % factor) nums)))
+7

, . .

(def nums [123456789012 123456789012])

(for [num nums] 
    (map #(Integer. (apply str %)) 
          (partition 4 (str num))))
;; => ((1234 5678 9012) (1234 5678 9012))
+4
(def nums [123456789012 123456789012])

(defn part-int [l n] 
  (map #(Integer. (apply str %)) 
    (partition l (str n))))

(map (partial part-int 4) nums)
;; => ((1234 5678 9012) (1234 5678 9012))
+2

@nickik

(partition 3
  (map #(Integer. (apply str %))
       (partition 4 
         (apply concat (map str nums)))))
+2
user=> (map #(->> % (str) (partition 4) (map (fn [s] (read-string (apply str s))))) nums)
((1234 5678 9012) (1234 5678 9012))

.

+2

Source: https://habr.com/ru/post/1771809/


All Articles