prologprolog-assert

Prolog Dynamic Predicates Basic Usage


with this knowledge base using https://swish.swi-prolog.org

:- dynamic happy/1.

go:-
    assert(happy(mia)),
    write(happy(mia)).

if I run go. I get

happy(mia)
true

If I just have

:- dynamic happy/1.

assert(happy(mia)).

and run happy(mia), I get false.

What fundamental concept am I missing please?


Solution

  • When you write:

    assert(happy(mia)).
    

    you are (re)defining the predicate assert/1, not calling it as in your definition of the go/0 predicate. Thus, happy(mia) is never added to the database. The query fails as the predicate happy/1 is know by the system (thanks to the dynamic/1 directive) but have no clauses.

    Most Prolog systems prevent the redefinition of standard built-in predicates. But assert/1 is a legacy/deprecated predicate. That explains why SWI-Prolog doesn't complain about the redefinition. Always use the standard assertz/1 predicate instead of assert/1.