Search code examples
prolog

How does Prolog optimize multiple calls to the same fact with same arguments


For example if I have this:

expensive(X, Y) :- % ... .

cheap(X, Y) :- expensive(X, Y), % ...
cheap2(X, Y) :- expensive(X, Y), % ...

and I call this:

perft(X, Y) :- expensive(X, Y), cheap(X, Y) , \+ cheap2(X, Y).

This is just hypothetical example, the question is does Prolog optimize the multiple calls to expensive fact, or do I have to find a better way to write this query so it doesn't call expensive fact twice, maybe cache the result somehow?


Solution

  • Prolog doesn’t optimize that away. I suspect because predicates can have side effects. It might read/write a file or print something to the terminal and so on. So Prolog can’t be sure that you don't get something different if you eliminate those duplicate calls.

    That said, you can use tabling to memoize individual predicates:

    :- table expensive/2.
    
    expensive(X, Y) :- ...