devil0150
devil0150

Reputation: 1469

Prolog fails without trying any of the RHS rules

I have this code:

res([],M,M).
res([[A,B]|G],inM,M) :-
    dfs(A, [[A,B]|G], [], [], Out),
    processResponse(Out,inM,M1),
    dfs(B, [[A,B]|G], [], [], Out2),
    processResponse(Out2,M1,M2),
    res(G,M2,M).

If I run res([],[],M), on the interpreter, it works fine and returns M = [].

If I run res([[a,b]],[],M), it fails. I tried looking at the trace and it fails immediately on res without even trying dfs or any of the other rules. If I write the rules directly on the interpreter, with the same input, they work fine.

I'm using SWI Prolog. Why does this happen? What should I change to make this work?

Upvotes: 1

Views: 110

Answers (1)

false
false

Reputation: 10120

You already got the right answers in the comments by some experienced Prolog programmers. But maybe pause for a while and consider how you could find such errors.

The nice thing in Prolog is that programs can be generalized in a very simple manner: By removing goals and by removing subterms. If such a generalized program fails as well, there has to be an error in the remaining fragment. In your example this would be:

:- op(950, fy, *).
*_.

res([],_/*M*/,_/*M*/).
res([_/*[A,B]*/|_/*G*/],inM,_/*M*/) :-
    * dfs(A, [[A,B]|G], [], [], Out),
    * processResponse(Out,inM,M1),
    * dfs(B, [[A,B]|G], [], [], Out2),
    * processResponse(Out2,M1,M2),
    * res(G,M2,M).

?- res([_/*[a,b]*/],[],M).

The query here still fails, so the error has to be in the remaining visible part.

Upvotes: 1

Related Questions