Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 506
Gilgamesz Avatar asked Oct 31 '22 02:10

Gilgamesz


1 Answers

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.

like image 104
mat Avatar answered Dec 14 '22 05:12

mat