Path: nntp.eternal-september.org!news.eternal-september.org!eternal-september.org!.POSTED!not-for-mail From: "B. Pym" Newsgroups: comp.lang.lisp Subject: Re: Newbie: reverse or append? Date: Sun, 29 Jun 2025 23:33:43 -0000 (UTC) Organization: A noiseless patient Spider Lines: 64 Message-ID: <103sigm$1p8bb$1@dont-email.me> MIME-Version: 1.0 Content-Type: text/plain; charset=iso-8859-1 Injection-Date: Mon, 30 Jun 2025 01:33:43 +0200 (CEST) Injection-Info: dont-email.me; posting-host="73560aae7c7612a4b7ed1e3f886ec647"; logging-data="1876331"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18pssPJX3EnqQLbTutem2qb" User-Agent: XanaNews/1.18.1.6 Cancel-Lock: sha1:YbAFgqB3ozWy5WmLZ2GUFZTzswg= Pascal Costanza wrote: > Tyro wrote: > > I wrote two recursive versions of a function that takes a list, an > > index and an empty list and returns three values: > > 1. The list of elements before the element at the given index > > 2. The element at the given index > > 3. The rest of the list after the given index > > > For example, (test1 '(a b c d e f) 3 nil) would return > > (A B C) > > D > > (E F) > > > The functions are: > > (defUn test1 (lst ind bef) > > (cond ((null lst) (values (reverse bef) nil (cdr lst))) > > ((= ind 0) (values (reverse bef) (car lst) (cdr lst))) > > (t (test1 (cdr lst) (- ind 1) (cons (car lst) bef))))) > > > (defUn test2 (lst ind bef) > > (cond ((null lst) (values bef nil (cdr lst))) > > ((= ind 0) (values bef (car lst) (cdr lst))) > > (t (test2 (cdr lst) (- ind 1) (append bef (list (car > > lst))))))) > > It seems to me that you are trying to program in Scheme instead of > Common Lisp. ;) > > Here is a version of what you are trying to do using Common Lisp's LOOP > facility: > > (defun test3 (list index) > (loop with at > for element in list > for i = 0 then (1+ i) > if (< i index) collect element into before > else if (= i index) do (setf at element) > else if (> i index) collect element into after > finally return (values before at after))) If one uses a Lispy language instead of CL, he can simply use recursion instead of a macro whose source measures 60 kilobytes. Gauche Scheme (define (test xs i :optional (before '())) (if (zero? i) (values (reverse before) (car xs) (cdr xs)) (test (cdr xs) (- i 1) (cons (car xs) before)))) gosh> (test '(a b c d e f) 5) (a b c d e) f () gosh> (test '(a b c d e f) 3) (a b c) d (e f) gosh> (test '(a b c d e f) 0) () a (b c d e f)