chicken-users
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Chicken-users] two procedures looking for a good home


From: Graham Fawcett
Subject: [Chicken-users] two procedures looking for a good home
Date: Thu, 21 Feb 2008 15:15:48 -0500

Hi folks,

I find that I use these two procedures frequently, and I'd love to see
them in an egg so I don't need to keep including them locally. Perhaps
is someone interested in working on a shared misc-combinators egg, to
store handy little things like this?

If such an egg exists and I'm not aware of it, please let me know.

Graham

(define (group-by keyproc lst #!optional (is-equal equal?))
  ;; group a list of elements by some key attribute.
  ;; the list must be in sorted order with respect to the key.
  ;; examples:
  ;; (group-by identity '(1 2 3 3 4 4 4)) --> ((1) (2) (3 3) (4 4 4))
  ;; (group-by car '((a 1) (a 2) (b 1))) --> '(((a 1) (a 2)) ((b 1)))
  (let loop ((lst lst) (acc '()))
   (if (null? lst)
       (reverse acc) ;; possibly remove the reversal?
       (let ((key (keyproc (car lst))))
         (receive (grouped rest)
             (span (lambda (item) (is-equal key (keyproc item))) lst)
           (loop rest (cons grouped acc)))))))

(define (key-on proc #!optional (comparator <))
  ;; Define a comparator function for a sort. E.g. to sort a list of
  ;; lists by their first items, using string-case-insensitive
  ;; comparison: (sort lst (key-on first string-ci<?))
  (lambda (a b) (comparator (proc a) (proc b))))




reply via email to

[Prev in Thread] Current Thread [Next in Thread]