Sujet : Re: Newbie: reverse or append?
De : Nobody447095 (at) *nospam* here-nor-there.org (B. Pym)
Groupes : comp.lang.lispDate : 30. Jun 2025, 00:33:43
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <103sigm$1p8bb$1@dont-email.me>
User-Agent : XanaNews/1.18.1.6
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)