[Common Lisp] Review my solution, please.

This topic is 3025 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

Hey! I'm reading Paul Graham's ANSI Common Lisp, and I was doing an exercise, this one:
Quote:
 Define iterative and recursive versions of a function that takes an object e and vector v, and returns a list of all the objects that immediately precede e in v: > (precedes #\a "abracadabra") (#\c #\d #\r)
I came up with solutions but the iterative one is ugly. The ugliness consists mostly of the repeated code (cadr v) (cadr v) etc. I've been thinking about better ways to do it, but I can't come up with anything; can you? I'm a little uncomfortable with iteration still. :P EDIT: Managed to make it a little better (prec-2i).
(defun prec-r (e v)
(and (cdr v)
(cons (car v) (prec-r e (cdr v)))
(prec-r e (cdr v)))))

(defun prec-i (e v)
(let ((a nil))
(do* ((v v (cdr v))
(cur (car v) (car v)))
((not (cdr v)) a)
(if (eql next e)
(push cur a)))))

(defun prec-2i (e v)
(let ((a nil))
(do ((eq? nil (eql (cadr v) e)))
((not (cdr v)) (reverse a))
(if eq?
(push (car v) a))
(pop v))))


[Edited by - tufflax on November 10, 2009 8:54:10 PM]