Article View: comp.lang.prolog
Article #83Re: transitive and symetric relations
From: Matthew Huntbach
Date: Tue, 11 Aug 1992 13:15
Date: Tue, 11 Aug 1992 13:15
46 lines
1783 bytes
1783 bytes
From: swk@seymour.mlb.semi.harris.com (Song W. Koh) >prolog beginner. I am having trouble describing transitive and >symetric relations without stack overflows. Things like: > >distance(X,Y,D) :- distance(Y,X,D). > >and > >distance(X,Z,D) :- distance(X,Y,D1), distance(Y,Z,D2), D is D1 + D2. No need for complex solutions involving meta-interpreters. I beleive the reasons why novices commonly make mistakes like this is that Prolog is taught as a mysterious theorem-proving system, rather than as just another programming language. If it were taught in the latter way, even novices would soon see that the first clause above will lead straight to a loop. You need to represent your known distances as facts with a separate predicate: dist(a,b,4). dist(b,c,5). etc. Now have: distance(X,Y,D) :- dist(X,Y,D). distance(X,Y,D) :- dist(Y,X,D). distance(X,Y,D) :- dist(X,Z,D1),distance(Z,Y,D2),D is D1+D2. OK, but this can still loop, consider: dist(a,b,4). dist(b,c,5). dist(a,c,3). dist(a,d,2). dist(d,e,1). with query: distance(a,e,D). The effect will be to cycle round teh loop in the graph. You need to keep a record of points 'visited' to prevent cycles like this. Think about it a bit more. Matthew Huntbach
Technical Details
Message-ID:
<1992Aug11.131542.18608@dcs.qmw.ac.uk>Path:
arc1-ca.pugleaf.net!sparky!uunet!mcsun!uknet!qmw-dcs!usenetReferences:
<SWK.92Aug10220513@seymour.mlb.semi.harris.com>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!sparky!uunet!mcsun!uknet!qmw-dcs!usenet From: mmh@cs.qmw.ac.uk (Matthew Huntbach) Newsgroups: comp.lang.prolog Subject: Re: transitive and symetric relations Message-ID: <1992Aug11.131542.18608@dcs.qmw.ac.uk> Date: 11 Aug 92 13:15:42 GMT References: <SWK.92Aug10220513@seymour.mlb.semi.harris.com> Sender: usenet@dcs.qmw.ac.uk (Usenet News System) Distribution: comp.lang.prolog Organization: Computer Science Dept, QMW, University of London, UK. Lines: 46 Nntp-Posting-Host: tea.dcs.qmw.ac.uk