Python syntax in Lisp and Scheme

Pascal Costanza costanza at web.de
Wed Oct 8 07:04:56 EDT 2003


Terry Reedy wrote:
> "Pascal Costanza" <costanza at web.de> wrote in message
> news:blu4q0$1568$1 at f1node01.rhrz.uni-bonn.de...
> 
>>What about dealing with an arbitrary number of filters?
> 
> 
> [macro snipped]
> 
> What about it?  Using macros for somewhat simple functions stikes me
> as overkill.

You're right. The use of with-collectors makes it more appropriate to 
express it as a macro, but of course, one can use a simple function when 
you don't stick to with-collectors.

> 
>>An example:
>>
>> > (predicate-collect '(-5 -4 -3 -2 -1 0 1 2 3 4 5)
>>     (function evenp)
>>     (lambda (n) (< n 0))
>>     (lambda (n) (> n 3)))
>>(-4 -2 0 2 4)
>>(-5 -3 -1)
>>(5)
>>(1 3)
> 
> 
> In Python:
> 
> def  multisplit(seq, *preds):
>     predn = len(preds)
>     bins = [[] for i in range(predn+1)]
>     predpends = [(p,b.append) for (p,b) in zip(preds,bins)]
>     rpend = bins[predn].append
>     for item in seq:
>         for pred,pend in predpends:
>             if pred(item):
>                 pend(item)
>                 break
>         else: rpend(item)
>     return bins
> 
> multisplit(range(-5,6), lambda i: not i%2, lambda i: i<0, lambda i:
> i>3)
> 
> [[-4, -2, 0, 2, 4], [-5, -3, -1], [5], [1, 3]]

For the sake of completeness, here is the Lisp version:

(defun predicate-collect (list &rest predicates)
   (let ((table (make-hash-table))
         (preds (append predicates
                        (list (constantly t)))))
     (dolist (elem list)
       (loop for pred in preds
             until (funcall pred elem)
             finally (push elem (gethash pred table))))
     (mapcar (lambda (pred)
               (nreverse (gethash pred table)))
             preds)))


? (predicate-collect
    '(-5 -4 -3 -2 -1 0 1 2 3 4 5)
    (function evenp)
    (lambda (n) (< n 0))
    (lambda (n) (> n 3)))

((-4 -2 0 2 4) (-5 -3 -1) (5) (1 3))


Pascal





More information about the Python-list mailing list