2010/8/10 Carlos Torres <[email protected]>
> Hi to everyone,
>
> I'm trying to create a function that takes a simple list and returns the
> number of zeros in the list.
> So I'm assuming that they will enter a list containing only numbers.
> This is what I have so far, but it only works when the list empty. Can
> somebody tell me what I'm missing?
>
> (defn count-zeros
> "Returns the numbers of zero in a simple sequence of numbers"
> [list1]
> (cond
> (empty? list1) 0
> (not (zero? (first list1))) 0
> :else
> (recur (+ 1 (count-zeros (rest list1))))))
>
Hi Carlos, your function can be written:
(defn count-zeros [l] (reduce #(if (zero? %2) (inc %1) %1) 0 l))
or less cryptic with variable names
(defn count-zeros [l] (reduce (fn [nb-zeros elem] (if (zero? elem) (inc
nb-zeros) nb-zeros)) 0 l))
But if you really want to write it recursively, then you must understand you
cannot recur with the partial sum when your function expects a list. And it
does not make sense to recur and call count-zeros at the same time.
here is a working version, using recur:
(defn count-zeros [list1]
(loop [list1 (seq list1) nb-zeros 0]
(if list1
(recur (next list1) (if (zero? (first list1)) (inc nb-zeros)
nb-zeros))
nb-zeros)))
HTH,
--
Laurent
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en