This is the mail archive of the guile@cygnus.com mailing list for the guile project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: list-split


Sascha Ziemann <szi@aibon.ping.de> wrote:
> is there another way to split a list than to use list-head and
> list-tail?
> I would like to avoid running twice through the list to the point where
> the list should be splitted.

When you are so concerned about not going through the head of the list
list twice you may consider a destructive list split as the one below.

(define list-to-split '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18))

(define (split-list! lst n)
  (let* ((pcdr (list-cdr-ref lst (1- n)))
	 (tail (cdr pcdr)))
    (set-cdr! pcdr '())
    (cons lst tail)))

scm> (split-list! list-to-split 8)
((0 1 2 3 4 5 6 7) 8 9 10 11 12 13 14 15 16 17 18)

	Best regards
	Roland Orre
------------------------------+---------------------+-----------------
Roland Orre                   | O---O---O Studies of| orre@nada.kth.se
SANS, NADA, KTH               | |\ /|\ /  Artificial| 
S-100 44 Stockholm, Sweden    | O-O-O-O   Neural    |Wph:+46 8 7906984
------------------------------+ |/ \ /|   Systems   |Fax:+46 8 7900930
Dept. of Computing Science    | O---O-O  +---------|Mob:+46 70 8269748
Royal Institute of Technology |          |http://www.nada.kth.se/~orre
------------------------------+----------+----------------------------