Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure: How to count occurrences in a list?

Tags:

clojure

I'm still pretty new to clojure, so I apologize if this a bit trivial. Basically, the issue is in the "then" part of the if statement: (if (symbol? (first slist)).

;counts the number of occurences of 
(defn count-occurrences [s slist]
 (if (empty? slist)
   0
   (if (symbol? (first slist))
     (if (= (first slist) s)
       (+ 1 (count-occurrences s (rest slist)))
       (+ 0 (count-occurrences s (rest slist))))
     (count-occurrences s (first slist)))))                  ;Problem on this line

(println (count-occurrences 'x '((f x) y (((x z) x)))))
like image 429
Chris Phillips Avatar asked Sep 02 '14 01:09

Chris Phillips


1 Answers

To count elements in a nested list, you could try this function:

(defn count-occurrences [s slist]
  (->> slist
       flatten
       (filter #{s})
       count))

Test:

user> (count-occurrences 'x '((f x) y (((x z) x))))
;; => 3
user> (count-occurrences 'y '((f x) y (((x z) x))))
;; => 1
user> (count-occurrences 'z '((f x) y (((x z) x))))
;; => 1
like image 183
Mark Karpov Avatar answered Sep 27 '22 22:09

Mark Karpov