Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

O(1) term look up

Tags:

prolog

I wish to be able to look up the existence of a term as fast as possible in my current prolog program, without the prolog engine traversing all the terms until it finally reaches the existing term.

I have not found any proof of it.. but I assume that given

animal(lion).
animal(zebra).
...
% thousands of other animals
...
animal(tiger).

The swi-prolog engine will have to go through thousands of animals trying to unify with tiger in order to confirm that animal(tiger) is in my prolog database.

In other languages I believe a HashSet would solve this problem, enabling a O(1) look up... However I cannot seem to find any hashsets or hashtables in the swi-prolog documentation.

Is there a swi-prolog library for hashsets, or can I somehow built it myself using term_hash\2?

Bonus info, I will most likely have to do the look up on some dynamically added data, either added to a hashset data-structure or using assertz

like image 874
Michelrandahl Avatar asked Mar 24 '15 23:03

Michelrandahl


2 Answers

All serious Prolog systems perform this O(1) lookup via hashing automatically and implicitly for you, so you do not have to do it yourself.

It is called argument-indexing, and you find this explained in all good Prolog books. See also "JIT (just-in-time) indexing" in more recent versions of many Prolog systems, including SWI. Indexing is applied to dynamically added clauses too, and is one reason why assertz/1 is slowed down and therefore not a good choice for data that changes more often than it is read.

You can also easily test this yourself by creating databases with increasingly more facts and seeing that the lookup time remains roughly constant when argument indexing applies.

like image 166
mat Avatar answered Oct 12 '22 18:10

mat


When the built-in first argument indexing is not enough (note that some Prolog systems also provide multi-argument indexing), depending on the system, you can construct your own indexing scheme using a built-in or library term hashing predicate. In the case of ECLiPSe, GNU Prolog, SICStus Prolog, SWI-Prolog, and YAP, look into the documentation of the term_hash/4 predicate.

like image 26
Paulo Moura Avatar answered Oct 12 '22 19:10

Paulo Moura