user1861156
user1861156

Reputation: 169

List of Lists trouble LISP

I'm new to LISP so I'm not very good at this... So my problem is, I've been given a structure (list of lists) and my job is to create a function that retrives the second item in each sub list (counting from 0). So in the end I would like to return (fruit fruit agent yard).

I can do the basic recursion calls that goes through the lists but I can't seem to figure out how to get the second item in the sub list.

Structure of the lists:

(defparameter *jack*
'((orange#8 apple fruit basment)
(pear#12 mango fruit basment)
(jones rabbit agent closet)
(jack dog agent yard)
))

Code I have so far:

(defun attempt(*data*)
(cond ((null *data*)
     nil
     )
    ((attempt (rest *data*)))
    ))

What I'm thinking is that I should be iterating through the list sub lists using first and rest but like I said, I can't figure it out. Help?

Upvotes: 1

Views: 482

Answers (3)

sçuçu
sçuçu

Reputation: 3070

yes you can define for this process you want a tail-recursive procedure;

(defun nths (n l)"returns list of nths of a list of lists l"
  (nths-aux n l '()))

(defun nths-aux (n l A)
  (if (null l) A;or (reverse A)
   (nths-aux n (cdr l)  (cons (nth n (car l)) A))))

Upvotes: 1

mck
mck

Reputation: 1404

CL-USER> (mapcar #'caddr *jack*)
(FRUIT FRUIT AGENT AGENT)

EDIT: If you want to practise your recursive approach, try:

(defun attempt (list-of-lists)
    (if (null list-of-lists) nil
        (cons (third (car list-of-lists))
              (attempt (cdr list-of-lists)))))

EDIT2: Tail-recursively:

(defun attempt-tail (list-of-lists)
    (labels ((iter (rest ans)
               (if (null rest) (nreverse ans)
                   (iter (cdr rest) (push (third (car rest)) ans)))))
      (iter list-of-lists nil)))

EDIT3: While I'm at it, here's the loop version:

(loop for list in *jack* collect (third list))

Upvotes: 3

Alexander L. Belikoff
Alexander L. Belikoff

Reputation: 5721

This is most probably what you are looking for:

(mapcar #'cadr *jack*)

Upvotes: 3

Related Questions