common-lisppractical-common-lisp

LISP function that takes 2 lists as parameters


After briefly talking about LISP in a past class, I have decided to jump in head first and try to learn CLISP (reading Seibel's PCL chpt 5). My question is in regards to writing a function that takes a set of lists as parameters. The first list is a series of indexes mapped to the second list. I want to pass a sequence of indexes and have it return the corresponding elements.

Here is the outline of my code so far. I wasn't sure if I could use nth and pass a list of arguments to it. I am not sure what the body-form should look like.

sys-info: CLISP 2.49 Win7

(defun get-elements('(nth (x y z) '(a b c)) )  
  "takes a list of arguments that returns corresponding elements from a list."
  (format t "The elements at index ~d are: ~%" x y z)
  ((maybe indexes go here)'(elements go here?)) 

The list (x y z) are the indexes and the data list (a b c) is some list of arbitrary elements. The evaluation is passed as data to the function get-elements. Am I even on the right track with this line of thinking?

Hints and pointers to relevant topics in LISP education are greatly appreciated.

postmortem: Upon re-examination of chpts 3-4, it would seem that PCL is a bit of a reach for a beginning programmer (at least for me). I can enter the code from the book, but I obviously don't have a deep understanding of the basic structure of the language. I will probably try a few gentler introductions to Lisp before undertaking PCL again.


Solution

  • I am not quite sure if this is what you are asking about, but you might want to try:

    (defun get-nth (index-list data-list)
      (mapcar (lambda (index)
                (nth index data-list))
              index-list))
    (get-nth '(0 1 0 2 0 3) '(a b c d e f))
    ==> (A B A C A D)
    

    Please take a look at

    More gentle introductions to Lisp: