In Clojure, empty sequences are not considered logically false, so
your code continues going after reducing col to an empty list. You
need to explicitly check whether the collection is empty, like so:
(defn list-length [col]
(if (empty? col)
0
(+ 1 (list-length (rest col)))))
Cheers,
Nadeem
On Sun, Dec 5, 2010 at 11:52 PM, HB <[email protected]> wrote:
> Hi,
> I'm trying to write a function that calculates the length of a list:
>
>
> (defn list-length [col]
> (if col
> (+ 1 (list-length(rest col)))
> 0))
>
>
> (list-length '(Java, Clojure, Scala))
>
> Upon running it in the REPL, I got the error:
> java.lang.StackOverflowError (test.clj:3)
>
> What is going wrong?
>
> --
> 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
--
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