View source with formatted comments or as raw
    1/*  Part of SWI-Prolog
    2
    3    Author:        Jan Wielemaker
    4    E-mail:        J.Wielemaker@vu.nl
    5    WWW:           http://www.swi-prolog.org
    6    Copyright (c)  2005-2025, VU University Amsterdam
    7                              CWI, Amsterdam
    8                              SWI-Prolog Solutions b.v.
    9    All rights reserved.
   10
   11    Redistribution and use in source and binary forms, with or without
   12    modification, are permitted provided that the following conditions
   13    are met:
   14
   15    1. Redistributions of source code must retain the above copyright
   16       notice, this list of conditions and the following disclaimer.
   17
   18    2. Redistributions in binary form must reproduce the above copyright
   19       notice, this list of conditions and the following disclaimer in
   20       the documentation and/or other materials provided with the
   21       distribution.
   22
   23    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   24    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   25    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   26    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   27    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   28    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   29    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   30    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   31    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   32    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   33    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   34    POSSIBILITY OF SUCH DAMAGE.
   35*/
   36
   37:- module(nb_set,
   38          [ empty_nb_set/1,		 % -EmptySet
   39            add_nb_set/2,		 % +Key, !Set
   40            add_nb_set/3,		 % +Key, !Set, ?New
   41            size_nb_set/2,		 % +Set, -Size
   42            nb_set_to_list/2,		 % +Set, -List
   43            gen_nb_set/2                 % +Set, -Key
   44          ]).   45:- use_module(library(debug), [assertion/1]).   46
   47/** <module> Non-backtrackable sets
   48
   49This library provides  a  non-backtrackabe  _set_   of  terms  that  are
   50variants of each other. It is primarily intended to implement distinct/1
   51from library(solution_sequences). The set is implemented as a hash table
   52that is built using non-backtrackable primitives, notably nb_setarg/3.
   53
   54The original version of this library   used  binary trees which provides
   55immediate ordering. As the trees were   not  balanced, performance could
   56get   really   poor.   The   complexity   of   balancing   trees   using
   57non-backtrackable primitives is too high. The  next iteration used _open
   58hash tables_, while the current incarnation   uses _closed hash tables_,
   59providing better perfomance and less space usage.
   60
   61@author Jan Wielemaker
   62*/
   63
   64initial_capacity(4).                       % initial hash-table size
   65
   66%!  empty_nb_set(-Set)
   67%
   68%   Create an empty non-backtrackable set.
   69
   70empty_nb_set(NbSet) :-
   71    initial_capacity(Capacity),
   72    Empty = empty(1),
   73    '$filled_array'(Buckets, buckets, Capacity, Empty),
   74    NbSet = nb_set(Empty, Capacity, 0, Buckets).
   75
   76%!  add_nb_set(+Key, !Set) is det.
   77%!  add_nb_set(+Key, !Set, ?New) is semidet.
   78%
   79%   Insert Key into the set. If  a   variant  (see  =@=/2) of Key is
   80%   already in the set, the set is unchanged and New is unified with
   81%   `false`. Otherwise, New is unified with   `true` and a _copy of_
   82%   Key is added to the set.
   83
   84add_nb_set(Key, Set) :-
   85    add_nb_set(Key, Set, _).
   86add_nb_set(Key, Set, New) :-
   87    Set = nb_set(Empty, Capacity, Size, Buckets),
   88    key_hash(Key, Hash),
   89    index(Hash, Capacity, KIndex),
   90        arg(KIndex, Buckets, StoredKey),
   91        (   same_term(StoredKey, Empty)
   92        ->  !,
   93            New = true,
   94            nb_setarg(KIndex, Buckets, Key),
   95            NSize is Size+1,
   96            nb_setarg(3, Set, NSize),
   97            (   NSize > Capacity//2
   98            ->  rehash(Set)
   99            ;   true
  100            )
  101        ;   Key =@= StoredKey
  102        ->  !,
  103            New = false
  104        ).
  105
  106%!  index(+Hash, +Capacity, -Index) is nondet.
  107%
  108%   Generate  candidate  values  for  Index,  starting  from  `Hash  mod
  109%   Capacity`, round tripping to 1 when Capacity is reached.
  110
  111index(Hash, Capacity, KIndex) :-
  112    KIndex0 is (Hash mod Capacity) + 1,
  113    next(KIndex0, Capacity, KIndex).
  114
  115next(KIndex, _, KIndex).
  116next(KIndex0, Capacity, KIndex) :-
  117    KIndex1 is 1+(KIndex0 mod Capacity),
  118    next(KIndex1, Capacity, KIndex).
  119
  120rehash(Set) :-
  121    Set = nb_set(Empty, Capacity, Size, Buckets),
  122    NCapacity is Capacity*2,
  123    '$filled_array'(NBuckets, buckets, NCapacity, Empty),
  124    nb_setarg(2, Set, NCapacity),
  125    nb_setarg(3, Set, 0),
  126    nb_linkarg(4, Set, NBuckets),
  127    forall(between(1, Capacity, I),
  128           reinsert(I, Empty, Buckets, Set)),
  129    arg(3, Set, NewSize),
  130    assertion(NewSize == Size).
  131
  132:- det(reinsert/4).  133reinsert(KIndex, Empty, Buckets, Set) :-
  134    arg(KIndex, Buckets, Key),
  135    (   same_term(Key, Empty)
  136    ->  true
  137    ;   add_nb_set(Key, Set, true)
  138    ).
  139
  140%!  key_hash(+Key, -Hash:integer) is det.
  141%
  142%   Compute a hash for Key. variant_hash/2 handles cyclic terms, hashing
  143%   them over a canonical form, so nothing special is needed here.
  144
  145key_hash(Key, Hash) :-
  146    variant_hash(Key, Hash).
  147
  148%!  nb_set_to_list(+NBSet, -OrdSet) is det.
  149%!  nb_set_to_list(-NBSet, +List) is det.
  150%
  151%   Get the elements of a an nb_set.   OrdSet  is sorted to the standard
  152%   order of terms, providing a set representation that is compatible to
  153%   library(ordsets).
  154
  155nb_set_to_list(NBSet, Set),
  156    NBSet = nb_set(Empty, Capacity, _Size, Buckets) =>
  157    buckets_to_list(1, Empty, Capacity, Buckets, List0),
  158    sort(List0, Set).
  159
  160buckets_to_list(KIndex, Empty, Capacity, Buckets, List) :-
  161    (   arg(KIndex, Buckets, Key)
  162    ->  (   same_term(Empty, Key)
  163        ->  KIndex1 is KIndex+1,
  164            buckets_to_list(KIndex1, Empty, Capacity, Buckets, List)
  165        ;   List = [Key|List1],
  166            KIndex1 is KIndex+1,
  167            buckets_to_list(KIndex1, Empty, Capacity, Buckets, List1)
  168        )
  169    ;   List = []
  170    ).
  171
  172%!  gen_nb_set(+Set, -Key) is nondet.
  173%
  174%   Enumerate the members of a set in the standard order of terms.
  175
  176gen_nb_set(nb_set(Empty, Capacity, _Size, Buckets), Key) =>
  177    between(1, Capacity, KIndex),
  178    arg(KIndex, Buckets, Key),
  179    \+ same_term(Empty, Key).
  180
  181%!  size_nb_set(+Set, -Size) is det.
  182%
  183%   Unify Size with the number of elements in the set
  184
  185size_nb_set(nb_set(_Empty, _Capacity, Sz, _Buckets), Size) =>
  186    Size = Sz