sequence rest and next

2010-09-03 Thread Abraham Varghese
I cannot understand between  ( next aseq)   and ( rest aseq) ...

Thanks
AV

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


Re: sequence rest and next

2010-09-03 Thread Meikel Brandmeyer
Hi,

On 3 Sep., 11:16, Abraham Varghese  wrote:

> I cannot understand between  ( next aseq)   and ( rest aseq) ...

next will realise the first item of the rest of aseq, while rest will
not. You can always express next in terms of rest:

(defn next
  [s]
  (seq (rest s)))

Sometimes you can also express rest in terms of next:

(defn rest
  [s]
  (or (next s) ()))

However this will not work for lazy sequences as returned by filter or
map since here the next item will be immediately realised.

The reason for this realisation is, that next returns nil when the
sequence is exhausted. However in order to be able to return nil you
have to know whether are actually no more items in the sequence. So
you have to realise it. The advantage is, that you can use next as a
predicate in if or when. The disadvantage is that you are not
completely lazy.

That's why rest was introduced (actually: rest was renamed to next and
new rest was introduced). It allows to return a value which decides
whether it's nil or not only when you call seq on it.

Usually you want to use rest. next is useful in loops, where you often
test on whether the sequence is exhausted (there it saves seq calls).
Or when you know you'll need the first item of the resulting sequence
anyway.

Hmm.. I'm not sure, I understand my exlpanation myself. Hope it helps
anyway.

Sincerely
Meikel

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