Jump to content
  • Advertisement
Sign in to follow this  
tufflax

[Common Lisp] Review my solution, please.

This topic is 3172 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
Advertisement
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!