On Mon, Nov 15, 2010 at 4:41 PM, Alan <a...@malloys.org> wrote:
> Yes, the API *does* suggest using seq to check for emptiness. (empty?
> x) is implemented as (not (seq x)). You certainly won't ever get
> improved performance by using empty? - at best you break even, most of
> the time you lose. For example:
>
> (if (empty? x)
>  ; empty branch
>  ; not-empty branch
> Can be replaced with
> (if (seq x)
>  ; not-empty branch
>  ; empty branch
>
> This is usually more readable, since the empty case tends to be less
> interesting.

I disagree. I tend to prefer to front-load the empty case, because
it's usually the base case of a (recur)sion. Getting it out of the way
quickly and early establishes both how the result is generated and the
semantics of many of the loop variables.

More generally, I like to test for, handle, and discard the
corner/special cases and quickie cases and then have the meat of the
function last. It gets the distractions out of the way to focus on the
main, common case (in loops, the iteration rather than the
termination).

> Further, you usually have to seq the object anyway if
> it's not empty, so the seq call becomes free except in the case where
> the collection is in fact empty:
> (if-let [x (seq x)]
>  ; do stuff with x
>  ; give up
>
> compared to:
> (if (not (seq x)) ; this is what empty? does
>  ; give up
>  (let [useful-var (seq x)]
>    ; do stuff with useful, seq'd version of x

Funny. My own use cases tend not to use seq explicitly at all. I'm
likely to have e.g.

(loop [s some-coll o nil]
  (if (empty? s)
    o
    (let [f (first s)]
       (blah blah blah s blah blah blah f blah blah blah)
       (recur (rest s) (conj o foobar)))))

or some similar control flow structure, where s gets first and rest
used on it, but not (directly) seq. If some-coll is not already a seq,
using these implicitly generates a seq view of it with seq; on every
iteration but the first, s is bound to a seq implementation already.

-- 
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