Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prolog efficiency: facts unification or list membership?

Tags:

prolog

Given these facts:

pos(a,1).
pos(b,2).
pos(c,3).

I want to find the position of a character. For example, pos(b,P) P=2.

Is it better to convert these facts to a list and do a membership check, like so:

member(X/P,[a/1,b/2,c/3])

I assume that the first option is better, but can anyone explain the pros and cons of each approach?

Note, this is just a simple example. I will have many facts, e.g 100-1000 and will have to do this check many more times, e.g. 100k+.

like image 377
S0rin Avatar asked Mar 14 '14 13:03

S0rin


1 Answers

A list implies a linear scan. I.e. the time to locate a element is proportional, in the worst case, to the number of elements in the list. But for facts for a static predicate, most Prolog implementations apply when possible what's called first argument indexing, which in this case would allow Prolog to call the correct clause for your pos/2 predicate when the first argument is instantiated without first trying (and failing) all the clauses that precede the correct one. Thus, you're comparing linear time, O(N), access to constant time access, O(1).

like image 184
Paulo Moura Avatar answered Sep 23 '22 10:09

Paulo Moura