[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Extract sublists

From: Nordlöw
Subject: Re: Extract sublists
Date: Wed, 18 Nov 2009 03:16:35 -0800 (PST)
User-agent: G2/1.0

On Nov 17, 4:37 pm, Ted Zlatanov <address@hidden> wrote:
> On Tue, 17 Nov 2009 05:22:51 -0800 (PST) Nordlöw <address@hidden> wrote:
> N> Is there a function for extracting sublists of lists?
> N> If not here is my suggestion for inclusion in Emacs.
> N> (defun sublist (list from to)
> N>   "Return a sublist of LIST, from FROM to TO.
> N> Counting starts at 0. Like `substring' but for lists."
> N>   (let (rtn (c from))
> N>     (setq list (nthcdr from list))
> N>     (while (and list (< c to))
> N>       (push (pop list) rtn)
> N>       (setq c (1+ c)))
> N>     (nreverse rtn)))
> N> ;; Use: (sublist '(a b) 0 0)
> N> ;; Use: (sublist '(a b) 0 1)
> N> ;; Use: (sublist '(a b) 1 2)
> N> ;; Use: (sublist '(a b) 0 2)
> It would be really nice if either FROM or TO could be a function or a
> number, so you can say "from 2 to the first place where the element
> passed to this function doesn't return t."  This is not a filter because
> you look for the first place the function fails.  Unfortunately it's
> efficient only if you walk through the list yourself so nthcdr won't be
> so useful.
> Ted

This gives superior performance in my benchmarks, thanks to very
little garbage collection.
For the case when to is nil it just returns (nthcdr from list) which I
hope is alright...

(defun sublist (list from &optional to)
  "Return a sublist of LIST, from FROM to TO.
If END is omitted, it defaults to the length of the sequence.
Counting starts at 0. Like `subseq' and `substring' but solely for
  (let ((start (nthcdr from list)))     ;start reference
    (if to (butlast start
                    (- (+ from (length start)) ;if extract list at the
end this makes it much faster


reply via email to

[Prev in Thread] Current Thread [Next in Thread]