Search code examples
lisp

lisp list with even position elements


I am trying to get a list from the list given as parameter that has only elements at even positions.

So if I have '(a b c d e f) I should get '(a c e). I also want to do it iteratively with do.

(defun pozpar (lst)
  (do ((l lst (cdr l))
       (y 0 (+ y 1))
       (x '() (cond ((eql 0 (mod y 2))
                     (cons (car l) x)))))
      ((null l) x)))
POZPAR
> (pozpar '(a b c d e f))
NIL

I don't see what's wrong with the code and why the list has only nil.


Solution

  • You missed the "else" clause of cond.

    Try this

    * (defun pozpar(lst)
        (do ((l lst (cdr l))
             (y 0 (+ y 1))
             (x '() (cond ((eql 0 (mod y 2)) (cons (car l) x))
                          (t x))))
            ((null l) x)))
    
    * (reverse (pozpar '(a b c d e f)))
    (A C E)