Search code examples
inputprologrulefactprolog-assert

How to assert new rule from user input (PROLOG)


I want to accept users' input, i.e. [garfield, hates, blacky]. hates/2 doesn't exist currently.

In my database,

process:-
    read(Input_List),
    add_rule(Input_List).

add_rule([X, Predicate, Y]):-
    assertz(Predicate(X, Y)).

But this doesn't work. Is it possible to use a variable as predicate, and facts? Or is there any other way to achieve this?


Solution

  • You can use the (=..)/2 operator called univ operator :

    add_rule(X, Predicate, Y) :-
        Fact =.. [Predicate, X, Y],
        assertz(Fact).
    

    Usage :

    ?- add_rule(garfield, hates, blacky).
    true.
    
    ?- hates(garfield, blacky).
    true.