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+.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With