• Re: Newbie: reverse or append?

    From B. Pym@Nobody447095@here-nor-there.org to comp.lang.lisp on Sun Jun 29 23:33:43 2025
    From Newsgroup: comp.lang.lisp

    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)
    --- Synchronet 3.21d-Linux NewsLink 1.2