Why am I getting a stack overflow in the following Clojure function:
(defn length
[xs]
(if ,(not= xs nil)
(println (+ 1 (length (rest xs))))
(println 0)))
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I think the idiomatic way of doing this is to call
seqon your collection.seqon a collection returnsnilif the collection is empty.This isn’t tail-recursive (you aren’t using
recurand can’t here) so this will still overflow the stack on very large collections.One tail-recursive version would be
This won’t overflow the stack even for huge collections but it’s still slow. Many Clojure collections implement the
Countedinterface and the built-incountfunction returns the length of those collections in constant time.