Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List operations in Lisp

I have been searching everywhere for the following functionality in Lisp, and have gotten nowhere:

  1. find the index of something in a list. example:

    (index-of item InThisList)
    
  2. replace something at a specific spot in a list. example:

    (replace item InThisList AtThisIndex) ;i think this can be done with 'setf'?
    
  3. return an item at a specific index. example:

    (return InThisList ItemAtThisIndex)
    

Up until this point, I've been faking it with my own functions. I'm wondering if I'm just creating more work for myself.

This is how I've been faking number 1:

(defun my-index (findMe mylist)
  (let ((counter 0) (found 1))
    (dolist (item mylist)
      (cond
        ((eq item findMe) ;this works because 'eq' checks place in memory, 
                  ;and as long as 'findMe' was from the original list, this will work.
         (setq found nil)
        (found (incf counter))))
  counter))
like image 626
helloandre Avatar asked Sep 05 '08 04:09

helloandre


2 Answers

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.

like image 161
Jeremy Avatar answered Oct 17 '22 10:10

Jeremy


  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!

like image 11
Sébastien RoccaSerra Avatar answered Oct 17 '22 10:10

Sébastien RoccaSerra