Gilgamesz
Gilgamesz

Reputation: 5073

Memoizing goals in Prolog

Is it possible for Prolog to memoize computed goals?

By that I mean to say that Prolog should not recompute goals that were computed before.

So, for example, the same computations for me are:

goal([first, one], he, she, var(cat, 5)).
goal([first, one], he, she, var(cat, 5)).

but not

goal([first, one], he, she, var(cat, 6)).

So, in fact, it must be possible to unify that goals.

Upvotes: 5

Views: 1075

Answers (1)

mat
mat

Reputation: 40768

Many Prolog systems provide the ability to implicitly record such results. This is called tabling; see your Prolog system's documentation about how to enable it.

A nice thing about Prolog is that you can easily build a somewhat simpler (and much less powerful) variant of tabling yourself, using for examlpe assertz/1 to store and load computed results.

A very simple-minded implementation could look similar to:

:- dynamic memo_/1.

memo(Goal) :-
    (    memo_(Goal) -> true
    ;    Goal,
         assertz(memo_(Goal))
    ).

Caveat emptor...

That's of course not what full-fledged tabling will give you.

Upvotes: 2

Related Questions