【发布时间】:2014-12-02 02:26:34
【问题描述】:
我想要一个数字、20 和一个列表。 '(1 2 3 4 5 6 7 8 9 10),并返回一个集合,其中包含原始列表中每个值的两个值:原始值与该值除以 20 时的余数配对。如果原始值以某种方式键入余数,那就太好了,这样我就可以轻松检索产生特定余数的每个数字。基本上我想要一些功能func:
user=> (func 20 '(1 2 3 4 5 6 7 8 9 10))
'(:0 1, :0 2, :2 3,... :20 0)
然而,我很难弄清楚如何遍历列表。谁能帮我理解如何独立使用列表的元素,然后如何返回 20 除以的元素以及是否返回余数?
我的想法是在计算平方根的程序中使用类似的东西。如果数字由余数键入,那么我可以查询集合以获取将输入除以余数 0 的所有数字。
这是我的初步处理方法。
;; My idea on the best way to find a square root is simple.
;; If I want to find the square root of n, divide n in half
;; Then divide our initial number (n) by all numbers in the range 0...n/2
;; Separate out a list of results that only only return a remainder of 0.
;; Then test the results in a comparison to see if the elements of our returned
;; list when squared are equal with the number we want to find a square root of.
;; First I'll develop a function that works with evens and then odds
(defn sqroot-range-high-end [input] (/ input 2))
(sqroot-range-high-end 36) ; 18
(defn make-sqrt-range [input] (range (sqroot-range-high-end (+ 1 input))))
(make-sqrt-range 36) ; '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18)
(defn zero-culler [input] (lazy-seq (remove zero? (make-sqrt-range input))))
(zero-culler 100) ; '(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18)
(defn odd-culler [input] (lazy-seq (remove odd? (zero-culler input))))
(odd-culler 100) ; '(2 4 6 8 10 12 14 16 18)
;;the following is where I got stuck
;;I'm new to clojure and programming,
;;and am just trying to learn in a way that I understand
(defn remainder-culler [input]
(if
(/ input (first odd-culler (input)))
input)
(recur (lazy-seq (input)))
)
(remainder-culler 100)
【问题讨论】:
-
你不需要在lazy-seq中包装remove,它已经是惰性的了。
标签: list loops if-statement clojure square-root