我正在寻找一种很好的方法来分割数字nClojure 中的数字我有以下两种方法:
(->> (str 942)
seq
(map str)
(map read-string)) => (9 4 2)
and...
(defn digits [n]
(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)
有没有更简洁的方法来执行此类操作?
第一种方法的简洁版本是
(defn digits [n]
(->> n str (map (comp read-string str))))
...你的第二个是
(defn digits [n]
(if (pos? n)
(conj (digits (quot n 10)) (mod n 10) )
[]))
惯用的替代方案
(defn digits [n]
(->> n
(iterate #(quot % 10))
(take-while pos?)
(mapv #(mod % 10))
rseq))
例如,
(map digits [0 942 -3])
;(nil (9 4 2) nil)
- 计算本质上是急切的,因为last digit in is the
first out。所以我们不妨使用
mapv
and rseq
(代替map
and reverse
)以更快地完成它。
- 该功能是传感器就绪的。
- 它仅适用于正数。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)