> What is the difference between rest and next?

This has to do with lazyness. I wrote an answer to that on
stackoverflow.

http://stackoverflow.com/questions/4288476/clojure-rest-vs-next

Should answer everthing.

> I'm confused, should I use empty? or not? when to use it?
> Why Clojure decided to handle an empty list as a not false? this is a
> big (if not) departure from Common Lisp?

The list is not nil because why should a empty list be nil but not en
empty set/map/vector. To make all of them nil would probebly make
other problems (100% sure we didn't do that would be intressting to
know).

So a common pattern is to just call seq or empty on the collection to
be sure that the empty list dosn't pass as true.
(On of the constant pain points when you work on books that are
written in CL or Scheme)


Next let my talk about the Stackoverflow:

If you use empty? you don't have one on small list but if the get
bigger you run in problems because you have to many nessted stacks.

The easy (and good) solution is to pass the running result onlong the
way. This can be done in diffrent ways.

First the CL Style where you creat a new function in you function that
then does all the work. (from
Ken Wesson)

(defn list-length [coll]
  (let [ll (fn [n s]
             (if s
               (recur (inc n) (next s))
               n))]
    (ll 0 (seq coll))))

I don't really like this because the core logic is somwhat hidden.

Then we could use arity functions. (Alex Osborne)

    (defn list-length
      ([coll]   (list-length coll 0))
      ([coll n] (if-let [s (seq coll)]
                     (recur (rest s) (inc n))
                      n)))

This is nice style in my opinion but I would do it like this:

(defn list-lenght [coll]
   (loop [coll coll n 0]
      (if (empty? coll)
          n
          (recur (rest coll) (inc n)))))

or with seq instead of empty?

(defn list-lenght [coll]
   (loop [coll coll n 0]
      (if (seq coll)
          (recur (rest coll) (inc n))
          n)))

Hope that helps a little.

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to