Forward Chaining in Prolog addP adds P to

  • Slides: 6
Download presentation
Forward Chaining in Prolog

Forward Chaining in Prolog

% add(P) adds P to DB and triggers forward chaining rules. add(P) : -

% add(P) adds P to DB and triggers forward chaining rules. add(P) : - clause(P, true), !. add(P) : FC Core dbug("Adding ~p. ~n", [P]), assert(P), foreach(if. Added(P, Actions), call(Actions)). % remove(P) removes P from DB, triggering if. Removed rules. remove(P) : dbug("Removing ~p. ~n", [P]), retract(P), foreach(if. Removed(P, Actions), call(Actions)).

Mapping rules into triggers % A=>B adds forward chaining rule to execute B whenever

Mapping rules into triggers % A=>B adds forward chaining rule to execute B whenever the facts % in A have all been added to the DB. % LHS is a conjunction ((P 1, P 2)=>Q) : - !, (P 1=>(P 2=>Q)). % LHS is a disjunction ((P 1; P 2)=>Q) : - !, (P 1=>Q), (P 2=>Q). % LHS is atomic. trigger already in DB? (P=>Q) : - if. Added(P, Q), !. % LHS is atomic. Add trigger to DB (P=>Q) : assert(if. Added(P, Q)), foreach(clause(P, true), fc. Do(Q)).

If-removed rules % A=/>B adds if. Removed rule to execute B whenever the %

If-removed rules % A=/>B adds if. Removed rule to execute B whenever the % assertions in A have all been removed from the database. ((P 1, P 2)=/>Q) : - !, (P 1=/>(P 2=/>Q)). ((P 1; P 2)=/>Q) : - !, (P 1=/>Q), (P 2=/>Q). (P=/>Q) : - assert(if. Removed(P, Q)). (=>X) : - add(X).

A test % FCTEST : - spouse(P 1, P 2) => add(spouse(P 2, P

A test % FCTEST : - spouse(P 1, P 2) => add(spouse(P 2, P 1)). : - spouse(P 1, P 2) =/> remove(spouse(P 2, P 1)). : - => spouse(adam, eve)). : - spouse(X, Y), female(X) => add(wife(X, Y)). : - => female(eve). : - female(X), male(X) => add(contradiction(female(X), male(X))). : - contradiction(P, Q) => file format(“CONTRADICTION: ~w and ~w. n”, [P, Q]).

| ? - [fctest]. Adding spouse(adam, eve). Adding spouse(eve, adam). yes | ? -

| ? - [fctest]. Adding spouse(adam, eve). Adding spouse(eve, adam). yes | ? - listing(if. Added). if. Added(spouse(A, B), add(spouse(B, A))). if. Added(a(A), (b(A), c(A)=>add(d(A)))). yes | ? - add(b(1)). Adding b(1). yes | ? - add(a(1)). Adding a(1). yes | ? - listing(if. Added). if. Added(spouse(A, B), add(spouse(B, A))). if. Added(a(A), (b(A), c(A)=>add(d(A)))). if. Added(b(1), (c(1)=>add(d(1)))). if. Added(c(1), add(d(1))). yes Fc in action | ? - add(c(1)). Adding c(1). Adding d(1). Yes | ? - b(X) => add(foo(X)), add(bar(X)). Adding foo(1). Adding bar(1). yes | ? - listing(if. Added). if. Added(spouse(A, B), add(spouse(B, A))). if. Added(a(A), (b(A), c(A)=>add(d(A)))). if. Added(b(1), (c(1)=>add(d(1)))). if. Added(c(1), add(d(1))). if. Added(b(A), (add(foo(A)), add(bar(A)))). yes