how can I print all database facts in prolog

2019-05-25 02:47发布

问题:

I have a database in prolog, all I want to do is enuamrate through its element and print one by one. How can this be done?

fact(is(mike,asthmatic)).
fact(has(andy,highPressure)).
fact(is(mike,smoker)).

I have written this, which works ok but it removes elements from the database, so I want to access them without removing.

print:- 
  retract(factA(P)),
    write(factA(P)),nl,
    fail.
  print.

回答1:

You might also consider using forall/2 predicate:

print:-
 forall(fact(P), writeln(P)).


回答2:

Well, you were almost there :

print :-
    fact(A),
    writeln(A),

First, we get a fact and print it.

    fail;true.

Then, we backtrack (through fail) until no solution is left. To avoid returning false, we add the disjunction with true.

Note that you can proceed differently, like :

print2 :-
    findall(Fact, fact(Fact), Facts),
    maplist(writeln, Facts).

But if you go that road, prefer @gusbro solution, it's better !



标签: prolog