List operations in Lisp

You can use setf and nth to replace and retrieve values by index.

(let ((myList '(1 2 3 4 5 6)))
     (setf (nth 4 myList) 101); <----
     myList)

(1 2 3 4 101 6)

To find by index you can use the position function.

(let ((myList '(1 2 3 4 5 6)))
     (setf (nth 4 myList) 101)
     (list myList (position 101 myList)))

((1 2 3 4 101 6) 4)

I found these all in this index of functions.


  1. find the index of something in a list.

In Emacs Lisp and Common Lisp, you have the position function:

> (setq numbers (list 1 2 3 4))
(1 2 3 4)
> (position 3 numbers)
2

In Scheme, here's a tail recursive implementation from DrScheme's doc:

(define list-position 
  (lambda (o l)
    (let loop ((i 0) (l l))
      (if (null? l) #f
          (if (eqv? (car l) o) i
              (loop (+ i 1) (cdr l)))))))

----------------------------------------------------

> (define numbers (list 1 2 3 4))
> (list-position 3 numbers)
2
> 

But if you're using a list as a collection of slots to store structured data, maybe you should have a look at defstruct or even some kind of Lisp Object System like CLOS.

If you're learning Lisp, make sure you have a look at Practical Common Lisp and / or The Little Schemer.

Cheers!


Answers:

  1. (position item sequence &key from-end (start 0) end key test test-not)
    http://lispdoc.com/?q=position&search=Basic+search

  2. (setf (elt sequence index) value)

  3. (elt sequence index)
    http://lispdoc.com/?q=elt&search=Basic+search
    NOTE: elt is preferable to nth because elt works on any sequence, not just lists