Donald
Donald

Reputation: 91

Prolog rule based system

Hi i have a rule based prolog system as shown below:

%forward chaining Production system
:-op(800,fx,if).        %set operators for if
:-op(700,xfx,then).     %then rules
:-op(300,xfy,or).
:-op(200,xfy,and).


%dynamic(....) allows predicate inside brackets fact to be asserted and retracted,
% here were are making fact (/1 means fact has 1 argument) dynamic so we can add and
% take facts from working memory.

:-dynamic(fact/1).

fact(has(smith,raisedIntraocularPressure)).        %list of facts
fact(had(smith,previousHeatAttack)).
fact(has(smith,leftQuadraticPain)).
fact(is(smith,heavySmoker)).
fact(is(jones,asthmatic)).
fact(has(jones,raisedIntraocularPressure)).
fact(is(jones,heavySmoker)).

forward:-
  new_fact(P),
  !,
  write('New fact '), write(P),nl,
  asserta(fact(P)),                        %adds a fact to working memory
  forward
;
  write('no more facts').


new_fact(Action):-
  if Condition then Action,
  not(fact(Action)),
  composedFact(Condition).

composedFact(Cond):-
  fact(Cond).

composedFact(C1 and C2):-
  composedFact(C1),
  composedFact(C2).

composedFact(C1 or C2):-
  composedFact(C1)
;
  composedFact(C2).


print:-


if has(Person,riskOfHeartAttack) and has(Person,previousHeartAttack)
then need(Person,digitalis).
if has(Person,leftQuadraticPain) and has(Person,highBloodPressure)
then has(Person,riskOfHeartAttack).
if has(Person,leftQuadraticPain)then has(Person,highBloodPressure).
if has(Person,highBloodPressure) and is(Person,heavySmoker)
then has(Person,riskOfHeartAttack).
if is(Person,asthmatic) and has(Person,riskOfHeartAttack) and has(Person,previousHeatAttack)then give(Person,preminolv).

not(X):-
 X,!,fail;true.

Okay first off i need it to create a command that prints the list of facts in the databases.

Secondly each rule is only used once. I need to change the code so that all the relevant facts are used. Apparently this can be done using a "bagof" function but i have no idea how to use it.

Thanks in advance =D

Upvotes: 1

Views: 1209

Answers (1)

Fred Foo
Fred Foo

Reputation: 363597

Print the list of facts:

print_facts :-
    findall(F, fact(F), Facts),
    maplist(writeln, Facts).

The findall/3 metapredicate is also the key to your second question, although you can also use bagof. See documentation, tutorial.

Upvotes: 2

Related Questions