Search code examples
functionclojuresequence

Using for-while or some other sequence functions


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

It gives me,

user> (9)

And if I change the sequence in the list like this,

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

Then it gives me,

user> (9 9)

Actually, I'm trying to get an empty list, if the integer n is divisible by any integer of sequence d; otherwise n. So, the question is, is there any seq function, or a combination of few, that can do the trick? Or do I have to use loop-recurr, or recursion, thing whatsoever?


Solution

  • I think that the function you are looking for is filter.

    Returns a lazy sequence of the items in coll for which (pred item) returns true. pred must be free of side-effects.

    The following function, divisible-by-fn, returns the number in the seq that is divisible by 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)
    

    ... but, in case, you need to get an empty list, if the integer n is divisible by any integer, d, in the seq; otherwise n, then

    (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