Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The iterative version proposed by Rainer is very nice, it's compact and more efficient since you traverse the sequence only one time; <strike>in contrast to the recursive version which calls <code>position</code> at every iteration and thus traverse the sub-sequence every time.</strike> (<strong>Edit:</strong> I'm sorry, I was completely wrong about this last sentence, see Rainer's comment)</p> <p>If a recursive version is needed, another approach is to advance the <code>start</code> until it meets the <code>end</code>, collecting the result along its way.</p> <pre><code>(defun precede (obj vec &amp;key (start 0) (end (length vec)) (test #'eql)) (if (or (null vec) (&lt; end 2)) nil (%precede-recur obj vec start end test '()))) (defun %precede-recur (obj vec start end test result) (let ((next (1+ start))) (if (= next end) (nreverse result) (let ((newresult (if (funcall test obj (aref vec next)) (adjoin (aref vec start) result) result))) (%precede-recur obj vec next end test newresult))))) </code></pre> <p>Of course this is just another way of expressing the <code>loop</code> version.</p> <p>test:</p> <pre><code>[49]&gt; (precede #\a "abracadabra") (#\r #\c #\d) [50]&gt; (precede #\a "this is a long sentence that contains more characters") (#\Space #\h #\t #\r) [51]&gt; (precede #\s "this is a long sentence that contains more characters") (#\i #\Space #\n #\r) </code></pre> <p>Also, I'm interested Robert, did your teacher say why he doesn't like using <code>adjoin</code> or <code>pushnew</code> in a recursive algorithm?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload