Sign in to follow this  

[Common Lisp] Review my solution, please.

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

If you intended to correct an error in the post then please contact us.

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)
       (if (eql e (cadr 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))
	  (next (cadr v) (cadr 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]

Share this post


Link to post
Share on other sites

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

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this