Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I print all database facts in prolog

Tags:

prolog

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.
like image 732
tomsky Avatar asked Oct 22 '25 15:10

tomsky


2 Answers

You might also consider using forall/2 predicate:

print:-
 forall(fact(P), writeln(P)).
like image 71
gusbro Avatar answered Oct 24 '25 23:10

gusbro


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 !

like image 42
m09 Avatar answered Oct 24 '25 22:10

m09