[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.lisp

Re: Better way to write this function?

William James

7/23/2015 7:53:00 PM

Gabe Garza wrote:

> Peter Seibel <peter@javamonkey.com> writes:
>
> > As part of a larger program I needed a function which given a number
> > (n) and a vector (row), returns the index into row of the n'th nil in
> > row. Here's the first (working) version I came up with:
> >
> > (defun nth-slot (n v)
> > "Find the nth nil cell in a vector v."
> > (loop with slots-seen = 0
> > for item across v
> > for idx from 0
> > counting (not item) into slots-seen
> > until (> slots-seen n)
> > finally (if (> slots-seen n) (return idx) (error "No slot"))))
>
> Here's how I'd write it (criticism welcome, of course!):
>
> (defun nth-slot (n vector)
> (loop for index from 0 below (length vector)
> if (null (aref vector index))
> do (decf n)
> (when (zerop n)
> (return index))))

Gauche Scheme:

(use srfi-43 :only (vector-index))

(define (nth-false-slot n vec)
(vector-index
(^x (zero? (dec! n (if x 0 1))))
vec))

(nth-false-slot 2 #(2 3 #f #f 5 6))
===>
3

--
As Helle "Hamas" Klein, political editor of Sweden's largest newspaper
Aftonbladet, boasts: "If the debate is going to be about whether there are
problems with immigrants, we don't want it". Welcome to Sweden, the country
where the media doesn't even pretend to champion freedom of speech, but openly
brags about censorship.
fjordman.blogspot.ca/2005/05/is-swedish-democracy-collapsing.html