Introduction
to recursion in prolog:
The recursion
in any language is a function that can call itself until the goal has been
succeed. In Prolog, recursion appears when a predicate contains a goal that
refers to itself.
As we have seen in the earlier chapters when a rule is called Prolog
create a new query with new variables. So, it makes no difference whether a
rule calls another rule or calls itself.
In Prolog and in any language, a recursive definition always has at
least two parts. A first fact that acts like a stopping condition and a rule
that call itself simplified. At each level the first fact is checked. If the
fact is true then the recursion ends. If not, then recursion continues.
A recursive rule must never call itself with the same arguments! If
that happens then the program will never end.
A Prolog program including Recursion:
parent(john,tom).
parent(john,bob). parent(john,sue). parent(mary,bob). parent(mary,sue).
parent(tom,mercy). parent(bob,clue). parent(bob,ray). parent(sue,clue).
parent(sue,ray).
parent(sou,vedik).
parent(vedik,harsh). parent(harsh,ved). parent(ved,milan). parent(milan,vishal).
parent(vishal,chakki).
male(john).
male(tom). male(ray). male(bob). female(mary). female(mercy). female(sue).
female(clue).
grandp(X,Y):-
parent(X,A),parent(A,Y).
brother(X,Y):-
parent(A,Y),parent(A,X),male(X).
sister(X,Y):-
parent(A,Y)parent(A,X),female(X).
uncle(X,Y):-
parent(A,X),brother(Y,A).
aunty(X,Y):-
parent(A,X),sister(Y,A).
cousins(X,Y):-
uncle(X,A),parent(A,Y), Y\=X.
ansc(X,Y):-
parent(X,Y).
ansc(X,Y):-
ansc(A,Y),parent(X,A).
Input:
parent(X,tom).
parent(X,mercy). parent(X,harsh). parent(X,ved). male(mary). ansc(X,chakki).
;
;
;
;
No comments:
Post a Comment