基于Prolog规则的系统

时间:2011-04-04 17:05:36

标签: prolog rule-engine

您好我有一个基于规则的prolog系统,如下所示:

%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.

好的,首先我需要它来创建一个打印数据库中事实列表的命令。

其次,每条规则只使用一次。我需要更改代码,以便使用所有相关的事实。显然,这可以使用“bagof”功能完成,但我不知道如何使用它。

提前致谢= D

1 个答案:

答案 0 :(得分:2)

打印事实清单:

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

findall/3 metapredicate也是第二个问题的关键,尽管您也可以使用bagof。请参阅documentationtutorial