1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2015 Ludovic Courtès <ludo@gnu.org>
4 ;;; This file is part of GNU Guix.
6 ;;; GNU Guix is free software; you can redistribute it and/or modify it
7 ;;; under the terms of the GNU General Public License as published by
8 ;;; the Free Software Foundation; either version 3 of the License, or (at
9 ;;; your option) any later version.
11 ;;; GNU Guix is distributed in the hope that it will be useful, but
12 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 ;;; GNU General Public License for more details.
16 ;;; You should have received a copy of the GNU General Public License
17 ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
19 (define-module (guix sets)
20 #:use-module (srfi srfi-1)
21 #:use-module (srfi srfi-9)
22 #:use-module (srfi srfi-26)
23 #:use-module (ice-9 vlist)
24 #:use-module (ice-9 match)
37 ;;; A simple (simplistic?) implementation of unordered persistent sets based
38 ;;; on vhashes that seems to be good enough so far.
40 ;;; Another option would be to use "bounded balance trees" (Adams 1992) as
41 ;;; implemented by Ian Price in 'pfds', which has faster union etc. but needs
42 ;;; an order on the objects of the set.
46 (define-record-type <set>
47 (%make-set vhash insert ref)
50 (insert set-insert-proc)
54 (cut vhash-cons <> #t <>))
56 (cut vhash-consq <> #t <>))
59 "Return a set containing the ARGS, compared as per 'equal?'."
63 "Return a set containing the ARGS, compared as per 'eq?'."
66 (define (list->set lst)
67 "Return a set with the elements taken from LST. Elements of the set will be
68 compared with 'equal?'."
69 (%make-set (fold %insert vlist-null lst)
73 (define (list->setq lst)
74 "Return a set with the elements taken from LST. Elements of the set will be
76 (%make-set (fold %insertq vlist-null lst)
80 (define-inlinable (set-contains? set value)
81 "Return #t if VALUE is a member of SET."
82 (->bool ((set-ref set) value (set-vhash set))))
84 (define (set-insert value set)
85 "Insert VALUE into SET."
86 (if (set-contains? set value)
88 (let ((vhash ((set-insert-proc set) value (set-vhash set))))
89 (%make-set vhash (set-insert-proc set) (set-ref set)))))
91 (define-inlinable (set-size set)
92 "Return the number of elements in SET."
93 (vlist-length (set-vhash set)))
95 (define (set-union set1 set2)
96 "Return the union of SET1 and SET2. Warning: this is linear in the number
97 of elements of the smallest."
98 (unless (eq? (set-insert-proc set1) (set-insert-proc set2))
99 (error "set-union: incompatible sets"))
101 (let* ((small (if (> (set-size set1) (set-size set2))
103 (large (if (eq? small set1) set2 set1)))
104 (vlist-fold (match-lambda*
106 (set-insert item result)))
110 (define (set->list set)
111 "Return the list of elements of SET."
114 (vlist->list (set-vhash set))))
116 ;;; sets.scm ends here