使用for-while或其他一些序列函数

时间:2013-11-21 08:25:48

标签: function clojure sequence

user> (for [n '(9) d '(2 3 5 7) :while (not= 0 (mod n d))] n)

它给了我,

user> (9)

如果我像这样更改列表中的序列,

user> (for [n '(9) d '(2 5 3 7) :while (not= 0 (mod n d))] n)

然后它给了我,

user> (9 9)

实际上,如果整数n可以被任何整数的序列d整除,我试图获得一个空列表;否则n。所以,问题是,是否有任何seq函数或少数组合可以解决这个问题?或者我必须使用loop-recurr或递归,无论如何?

1 个答案:

答案 0 :(得分:2)

我认为您正在寻找的功能是filter

  

返回coll中项目的延迟序列(pred item)   返回true。 pred必须没有副作用。

以下函数divisible-by-fn会返回seq中可被n整除的数字

(defn divisible-by-fn [your-integer your-seq]
  (filter #(zero? (mod your-integer %))your-seq))
(divisible-by-fn 9 '(2 5 3 7))
=>(3)

...但是,如果需要获得一个空列表,如果整数n可以被d中的任何整数seq整除;否则n,那么

(defn your-fn [your-integer your-seq]
(if-not (not-any? #(zero? (mod your-integer %))your-seq)
 ()
 your-integer)
)
(your-fn 9 '(2 5 3 7))
=> () 
(your-fn 11 '(2 5 3 7))
=> 11