t3x.org / nss / partition.html

(Nils' Scheme Snippets)

 
Paren matching: ON  |  Category: lists  |  Overview  |  Scheme Books  |  License
 

(partition proc1 list) => (list1 list2)

 
Purpose
Partition a list into elements with and without a given property. The predicate p specifies the property. The returned value contains two lists, where the first one holds the elements satisfying the property and the second one the elements not satisfying the property.
 
Arguments
p predicate
a source list
 
Example
(partition even? '(1 2 3 4 5)) => ((2 4) (1 3 5))
(define (partition p a)
  (letrec
    ((partition3
       (lambda (a r+ r-)
         (cond
           ((null? a)
             (list r+ r-))
           ((p (car a))
             (partition3 (cdr a) (cons (car a) r+) r-))
           (else (partition3 (cdr a) r+ (cons (car a) r-)))))))
    (partition3 (reverse a) '() '())))

Copyright (C) 2007 Nils M Holm <nmh @ t3x . org>