Re: How to solve a problem with an infinite loop [beginners question]
- From: Chip Eastham <hardmath@xxxxxxxxx>
- Date: Sat, 06 Oct 2007 18:55:51 -0700
On Oct 6, 5:35 pm, philipp.str...@xxxxxxxxx wrote:
Hi everybody,
I have the following grammar
gleich(a,b).
gleich(b,c).
gleich(A,B) :-
A=B.
gleich(A,B) :-
gleich(B,A).
gleich(A,B) :-
gleich(A,X),gleich(X,B).
I want to ask prolog the following questions (which should all lead to
the answer true):
gleich(a,a).
gleich(a,b).
gleich(b,a).
gleich(a,c).
gleich(c,a).
gleich(a,c) and gleich(c,a) leads to an infinity loop how can I avoid
this?
best wishes
Philipp
Hi, Philipp:
It seems to be a case of finding the connected components
of an undirected graph, or equivalently the transitive
closure of a relation.
In this generality it is necessary to avoid backtracking
into previously reached nodes in order to avoid looping
problems. Thus we have to retain a memory of what prior
nodes are visited in a path.
It's a good idea to use separate predicates for the
"elementary" facts (edges of the graph) and for the
"derived" facts (rules pertaining to transitive closure).
One approach is to assert dynamic facts corresponding
to the reachable nodes. Another approach shown below
dispenses with the dynamic predicates. We assume that
at least the first argument is "input" (bound).
gleich(a,b).
gleich(b,c).
gleichClosure(A,B) :- gClosure([A],B).
gClosure([A|_],A).
gClosure([H|T],B) :-
(gleich(H,X);gleich(X,H)),
not(member(X,[H|T])),
gClosure([X,H|T],B).
member(H,[H|_]).
member(X,[_|T]) :- member(X,T).
regards, chip
.
- Follow-Ups:
- Re: How to solve a problem with an infinite loop [beginners question]
- From: philipp . strack
- Re: How to solve a problem with an infinite loop [beginners question]
- References:
- How to solve a problem with an infinite loop [beginners question]
- From: philipp . strack
- How to solve a problem with an infinite loop [beginners question]
- Prev by Date: Re: How to solve a problem with an infinite loop [beginners question]
- Next by Date: Re: swi prolog + clpr question
- Previous by thread: Re: How to solve a problem with an infinite loop [beginners question]
- Next by thread: Re: How to solve a problem with an infinite loop [beginners question]
- Index(es):
Relevant Pages
|
|