我对 clojure 还是很陌生,所以如果这有点微不足道,我深表歉意。基本上,问题出在 if 语句的“then”部分:(if(符号?(第一个 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)))))
Run Code Online (Sandbox Code Playgroud)
要计算嵌套列表中的元素,您可以试试这个函数:
(defn count-occurrences [s slist]
(->> slist
flatten
(filter #{s})
count))
Run Code Online (Sandbox Code Playgroud)
测试:
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
Run Code Online (Sandbox Code Playgroud)