如何拆分一个数字在Clojure? [英] How to split a number in Clojure?

查看:124
本文介绍了如何拆分一个数字在Clojure?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个很好的方法来分割一个数字与 n 数字在Clojure我有这两个详细无效的方法:

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

和...

 (defn digits [n]; YUK !! 
(cons
(str(mod n 10))(lazy-seq 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))))
pre>

...第二个是

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

惯用替代

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

/ p>

 (map digit [0 942 -3])
;(nil(9 4 2)nil)




  • 计算本质上是急切的,因为 所以我们可以使用 mapv rseq (而不是 map

  • li>它只适用于正数。

I am looking for a nice method to split a number with n digits in Clojure I have these two 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 a more concise method for doing this type sort of operation?

解决方案

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.

这篇关于如何拆分一个数字在Clojure?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆