2

Don't need answer anymore. its done. Thanks !

a(S,E,[S|R]) :- S\=E,(c(S, N);c(N,S)),a(N,E,R),\+member(S,R).
a(X,X,P):- P=[X].

The above code cause out of local stack problem, Could someone tell me how to fix? Thanks.

SwordW
  • 592
  • 2
  • 6
  • 20
  • c(1,2). c(1,3).c(2,4).c(3,4). – SwordW Dec 02 '15 at 04:28
  • 1
    `A(S,E,[S|R]) :- ...` isn't valid Prolog syntax, so I doubt the code you are showing even executed. It would have thrown an error. Please show the code you actually tried. – lurker Dec 02 '15 at 12:14
  • 1
    I am so sorry, I mean a instead of A. Since Im asking a homework problem, to avoid showing answer online, I changed all the names and I made a horrible mistake. Thank you guys for pointing out – SwordW Dec 02 '15 at 14:45
  • 1
    Work harder on improving the quality of your question! Use proper code layout. Choose proper names. Write the queries you did, the answer(s) you expected and the answer(s) you got. – repeat Dec 02 '15 at 15:47
  • You should accept the answer given by @CapelliC if you found it acceptable. There's a checkmark that you click when viewing his answer. It's very unorthodox to edit your question to say it's answered. That should be evident from accepting the appropriate answer. Also, others may still want to offer answers just as useful alternatives or more information, if not for you, then for others reading the question and answers. – lurker Dec 02 '15 at 19:31

1 Answers1

1

To complete a visit of a graph with loops (introduced in your DAG from c(S, N);c(N,S)), we must check the path seen so far (just to say), but you attempt to inspect after it has been built. This 'logical loop' reflects in non termination of your code. The easier solution is to add an argument that holds the path seen so far:

a(S,E,P) :- visit(S,E,[S],P).

visit(X,X,P,R) :- reverse(P,R).
visit(S,E,P,R) :- (c(S,N);c(N,S)), \+memberchk(N,P), visit(N,E,[N|P],R).

yields

?- a(1,4,L).
L = [1, 2, 4] ;
L = [1, 3, 4] ;
false.

see this thread about some high level thoughts on this theme

Community
  • 1
  • 1
CapelliC
  • 59,646
  • 5
  • 47
  • 90
  • you are amazing, it works. And if I try more complicated graph, it may give me same answer twice. Do you know why? And thank you ! – SwordW Dec 02 '15 at 14:43
  • for example,i have c(10,14) and c(14,10). When it done with using (10,14), next time it will use (14,10). That is why I get same answer. Do you know how to fix it? – SwordW Dec 02 '15 at 16:25
  • 1
    @SwordW. How about accepting this answer by CapelliC as a sign of gratitude? And while we're at it... Please improve the quality of your question, so it becomes more approachable by others interested in it in the future: add all relevant code parts (not into a comment to your own question, but to the **question itself**). use proper code layout. add queries (and their respective answers) you have tried for testing, so others can reproduce the problem you were having. – repeat Dec 02 '15 at 17:31