Getting in Clojure Function.

Why do I get stack overflow in the following Clojure function:

(defn length
  [xs]
  (if ,(not= xs nil)
    (println (+ 1 (length (rest xs))))
    (println 0)))
+3
source share
2 answers

I think the idiomatic way to do this is to call seqin your collection. seqin collection returns nilif the collection is empty.

(defn length [xs]
  (if (seq xs)
      (inc (length (rest xs)))
      0))

This is not a recursive tail (you do not use recurand cannot here), so it will still overflow the stack in very large collections.

user> (println (length (range 1000000)))
;; stack overflow

One tail recursive option would be

(defn length [xs]
  (loop [xs xs
         acc 0]
    (if (seq xs)
        (recur (rest xs) (inc acc))
        acc)))

user> (println (length (range 1000000)))
1000000

, . Clojure Counted, count .

+10

seqs, rest nil, - :

(defn length 
   [xs]
   (if (not (empty? xs))
      (println (+ 1 (length (rest xs))))
      (println 0)))

(defn length
   [xs]
   (if ,(not= xs nil)
      (println (+ 1 (length (next xs))))
      (println 0)))
+4

Source: https://habr.com/ru/post/1712791/


All Articles