Why this query will output the correct answer?

I’m using: SWI-Prolog version 9.0.3

My code looks like this:

append([],Y,Y).
append([U|V],Y,[U|Z]) :- append(V,Y,Z).
reverse1([],[]).
reverse1([H|T],L) :- reverse1(T,X), append(X, [H], L).

My query looks like this:

?- reverse1(X,[1,2,3]).

I want the code to: Never stop. Because the X isn’t a complete list.

But what I’m getting is: X = [3, 2, 1]. :thinking: Why?

Have you tried using trace or gtrace?

1 Like

Sorry, I am a newbee in prolog.

I tried to trace the execution of reverse1(X,[1,2,3]). And I noticed it will choice to call append(X,[H],L) after calling reverse1(T,X).

So it will regard T and X as [] here.

I know, I subconsciously always thought of reverse1([],[]). as a RULE. But it is a fact. :upside_down_face:

It loops when you ask for a next answer (by a ‘;’).