How does this permutation algorithm work - prolog

ar([],[]).
ar([p(_,_)|L],L1):-ar(L,L2),L1=L2.
ar([p(X,Y)|L],L1):-ar(L,L2),L1=[p(X,Y)|L2].
(p stands for point, having the coordinates X and Y)
Please help me to understand how the result is being constructed, especially the part where L1 gets a new value, thanks!

The definition of your predicate ar/2 behaves like the powerset function, being a syntactic variant of the following (where X is restricted to terms of p/2):
% clause 1: base case
ps([], []).
% clause 2: omit the element X
ps([_X|Y], Z) :-
ps(Y, Z).
% clause 3: keep the element X
ps([X|Y], [X|Z]) :-
ps(Y, Z).
The predicates ps/2 (and your ar/2) basically backtrack to bind all sub-lists of the list in the first argument to that of the second argument. It achieves this with the choice represented by the second and third clauses: either omit or keep a list element when constructing the new list.
Consider what Prolog does when executing the goal ps([a,b],L):
ps([_|[b]], Z) :- ps([b], Z). (via clause 2, drop a).
ps([b|[]], Z) :- ps([], Z). (via clause 2, drop b; note that [b] = [b|[]]).
ps([], Z) binds Z = [] (via clause 1, gives solution 1).
ps([b|[]], [b|Z]) :- ps([], Z). (via clause 3, keep b).
ps([], Z) binds Z = [] (via clause 1, gives solution 2).
ps([_|[b]], [a|Z]) :- ps([b], Z). (via clause 3, keep a).
ps([b|[]], Z) :- ps([], Z). (via clause 2, drop b).
ps([], Z) binds Z = [] (via clause 1, gives solution 3).
ps([b|[]], [b|Z]) :- ps([], Z). (via clause 3, keep b).
ps([], Z) binds Z = [] (via clause 1, gives solution 4).
Each of the deepest levels which hit the 'base-case' of clause 1 return up the call stack. Each of these cases result in the following:
Drop both a and b: []
Drop a, keep b: [b]
Keep a, drop b: [a]
Keep both a and b: [a,b]
Thus, we can backtrack to generate [], [b], [a] and [a,b], i.e., the four sub-lists of [a,b].

First of all, note that this procedure does not compute a permutation, but a sort of sublist: a list with "some" points removed, where by "some" is said in general form (one of the solutions is the empty list and also other solution is the original list), assuming the input list is well formed.
If the input list is not well formed (it has one item which is not a "point") then the procedure will fail.
Now let's explain the three clauses of ar/2, which is a recursive procedure:
First clause,
ar([], []).
states that if the first argument is the empty list, then the second argument is also the input list; i.e. for an empty list the only "sublist" conforming with the rules of the procedure is also an empty list.
This is also the base case of the recursive procedure.
The second clause,
ar([p(_,_)|L], L1):-ar(L, L2), L1=L2.
can be rewritten without using the L2 variable because it will eventually unify with L1:
ar([p(_,_)|L], L1):-ar(L, L1).
This clause is skipping the head of the input list and continuing with recursion. Upon return of recursion it will unify the resulting list (second argument of ar/2 call) with the second argument of the head of the clause.
The third clause,
ar([p(X,Y)|L], L1):-ar(L, L2), L1=[p(X,Y)|L2].
can be, again, rewritten without using the L2 variable by means of building the resulting list in the head of the clause:
ar([p(X,Y)|L], [p(X,Y)|L1]):-ar(L,L1).
This clause will take the head of the input list, continue recursion with the tail and then unify second argument of the head of the clause with the item taken and the resulting list of the recursion. That is, it will keep the item (head) of the input list along with the result of recursion.
Also note that this procedure is not reversible, if called with the first argument uninstantiated and the second argument instantiated it will loop forever.

Related

Understanding Prolog Lists

I am trying to understand Prolog lists, and how values are 'returned' / instantiated at the end of a recursive function.
I am looking at this simple example:
val_and_remainder(X,[X|Xs],Xs).
val_and_remainder(X,[Y|Ys],[Y|R]) :-
val_and_remainder(X,Ys,R).
If I call val_and_remainder(X, [1,2,3], R). then I will get the following outputs:
X = 1, R = [2,3];
X = 2, R = [1,3];
X = 3, R = [1,2];
false.
But I am confused as to why in the base case (val_and_remainder(X,[X|Xs],Xs).) Xs has to appear as it does.
If I was to call val_and_remainder(2, [1,2,3], R). then it seems to me as though it would run through the program as:
% Initial call
val_and_remainder(2, [1,2,3], R).
val_and_remainder(2, [1|[2,3]], [1|R]) :- val_and_remainder(2, [2,3], R).
% Hits base case
val_and_remainder(2, [2|[3]], [3]).
If the above run through is correct then how does it get the correct value for R? As in the above case the value of R should be R = [1,3].
In Prolog, you need to think of predicates not as functions as you would normally in other languages. Predicates describe relationships which might include arguments that help define that relationship.
For example, let's take this simple case:
same_term(X, X).
This is a predicate that defines a relationship between two arguments. Through unification it is saying that the first and second arguments are the same if they are unified (and that definition is up to us, the writers of the predicate). Thus, same_term(a, a) will succeed, same_term(a, b) will fail, and same_term(a, X) will succeed with X = a.
You could also write this in a more explicit form:
same_term(X, Y) :-
X = Y. % X and Y are the same if they are unified
Now let's look at your example, val_and_remainder/3. First, what does it mean?
val_and_remainder(X, List, Rest)
This means that X is an element of List and Rest is a list consisting of all of the rest of the elements (without X). (NOTE: You didn't explain this meaning right off, but I'm determining this meaning from the implementation your example.)
Now we can write out to describe the rules. First, a simple base case:
val_and_remainder(X,[X|Xs],Xs).
This says that:
Xs is the remainder of list [X|Xs] without X.
This statement should be pretty obvious by the definition of the [X|Xs] syntax for a list in Prolog. You need all of these arguments because the third argument Xs must unify with the tail (rest) of list [X|Xs], which is then also Xs (variables of the same name are, by definition, unified). As before, you could write this out in more detail as:
val_and_remainder(X, [H|T], R) :-
X = H,
R = T.
But the short form is actually more clear.
Now the recursive clause says:
val_and_remainder(X, [Y|Ys], [Y|R]) :-
val_and_remainder(X, Ys, R).
So this means:
[Y|R] is the remainder of list [Y|Ys] without X if R is the remainder of list Ys without the element X.
You need to think about that rule to convince yourself that it is logically true. The Y is the same in second and third arguments because they are referring to the same element, so they must unify.
So these two predicate clauses form two rules that cover both cases. The first case is the simple case where X is the first element of the list. The second case is a recursive definition for when X is not the first element.
When you make a query, such as val_and_remainder(2, [1,2,3], R). Prolog looks to see if it can unify the term val_and_remainder(2, [1,2,3], R) with a fact or the head of one of your predicate clauses. It fails in its attempt to unify with val_and_remainder(X,[X|Xs],Xs) because it would need to unify X with 2, which means it would need to unify [1,2,3] with [2|Xs] which fails since the first element of [1,2,3] is 1, but the first element of [2|Xs] is 2.
So Prolog moves on and successfully unifies val_and_remainder(2, [1,2,3], R) with val_and_remainder(X,[Y|Ys],[Y|R]) by unifying X with 2, Y with 1, Ys with [2,3], and R with [Y|R] (NOTE, this is important, the R variable in your call is NOT the same as the R variable in the predicate definition, so we should name this R1 to avoid that confusion). We'll name your R as R1 and say that R1 is unified with [Y|R].
When the body of the second clause is executed, it calls val_and_remainder(X,Ys,R). or, in other words, val_and_remainder(2, [2,3], R). This will unify now with the first clause and give you R = [3]. When you unwind all of that, you get, R1 = [Y|[3]], and recalling that Y was bound to 1, the result is R1 = [1,3].
Stepwise reproduction of Prolog's mechanism often leads to more confusion than it helps. You probably have notions like "returning" meaning something very specific—more appropriate to imperative languages.
Here are different approaches you can always use:
Ask the most general query
... and let Prolog explain you what the relation is about.
?- val_and_remainder(X, Xs, Ys).
Xs = [X|Ys]
; Xs = [_A,X|_B], Ys = [_A|_B]
; Xs = [_A,_B,X|_C], Ys = [_A,_B|_C]
; Xs = [_A,_B,_C,X|_D], Ys = [_A,_B,_C|_D]
; Xs = [_A,_B,_C,_D,X|_E], Ys = [_A,_B,_C,_D|_E]
; ... .
So Xs and Ys share a common list prefix, Xs has thereafter an X, followed by a common rest. This query would continue producing further answers. Sometimes, you want to see all answers, then you have to be more specific. But don't be too specific:
?- Xs = [_,_,_,_], val_and_remainder(X, Xs, Ys).
Xs = [X,_A,_B,_C], Ys = [_A,_B,_C]
; Xs = [_A,X,_B,_C], Ys = [_A,_B,_C]
; Xs = [_A,_B,X,_C], Ys = [_A,_B,_C]
; Xs = [_A,_B,_C,X], Ys = [_A,_B,_C]
; false.
So here we got all possible answers for a four-element list. All of them.
Stick to ground goals when going through specific inferences
So instead of val_and_remainder(2, [1,2,3], R). (which obviously got your head spinning) rather consider val_and_remainder(2, [1,2,3], [1,3]). and then
val_and_remainder(2, [2,3],[3]). From this side it should be obvious.
Read Prolog rules right-to-left
See Prolog rules as production rules. Thus, whenever everything holds on the right-hand side of a rule, you can conclude what is on the left. Thus, the :- is an early 1970s' representation of a ←
Later on, you may want to ponder more complex questions, too. Like
Functional dependencies
Does the first and second argument uniquely determine the last one? Does X, Xs → Ys hold?
Here is a sample query that asks for Ys and Ys2 being different for the same X and Xs.
?- val_and_remainder(X, Xs, Ys), val_and_remainder(X, Xs, Ys2), dif(Ys,Ys2).
Xs = [X,_A,X|_B], Ys = [_A,X|_B], Ys2 = [X,_A|_B], dif([_A,X|_B],[X,_A|_B])
; ... .
So apparently, there are different values for Ys for a given X and Xs. Here is a concrete instance:
?- val_and_remainder(x, [x,a,x], Ys).
Ys = [a,x]
; Ys = [x,a]
; false.
There is no classical returning here. It does not return once but twice. It's more of a yield.
Yet, there is in fact a functional dependency between the arguments! Can you find it? And can you Prolog-wise prove it (as much as Prolog can do a proof, indeed).
From comment:
How the result of R is correct, because if you look at my run-though
of a program call, the value of Xs isn't [1,3], which is what it
eventually outputs; it is instead [3] which unifies to R (clearly I am
missing something along the way, but I am unsure what that is).
This is correct:
% Initial call
val_and_remainder(2, [1,2,3], R).
val_and_remainder(2, [1|[2,3]], [1|R]) :- val_and_remainder(2, [2,3], R).
% Hits base case
val_and_remainder(2, [2|[3]], [3]).
however Prolog is not like other programming languages where you enter with input and exit with output at a return statement. In Prolog you move forward through the predicate statements unifying and continuing with predicates that are true, and upon backtracking also unifying the unbound variables. (That is not technically correct but it is easier to understand for some if you think of it that way.)
You did not take into consideration the the unbound variables that are now bound upon backtracking.
When you hit the base case Xs was bound to [3],
but when you backtrack you have look at
val_and_remainder(2, [1|[2,3]], [1|R])
and in particular [1|R] for the third parameter.
Since Xs was unified with R in the call to the base case, i.e.
val_and_remainder(X,[X|Xs],Xs).
R now has [3].
Now the third parameter position in
val_and_remainder(2, [1|[2,3]], [1|R])
is [1|R] which is [1|[3]] which as syntactic sugar is [1,3] and not just [3].
Now when the query
val_and_remainder(2, [1,2,3], R).
was run, the third parameter of the query R was unified with the third parameter of the predicate
val_and_remainder(X,[Y|Ys],[Y|R])
so R was unified with [Y|R] which unpon backtracking is [1,3]
and thus the value bound to the query variable R is [1,3]
I don't understand the name of your predicate. It is a distraction anyway. The non-uniform naming of the variables is a distraction as well. Let's use some neutral, short one-syllable names to focus on the code itself in its clearest form:
foo( H, [H | T], T). % 1st clause
foo( X, [H | T], [H | R]) :- foo( X, T, R). % 2nd clause
So it's the built-in select/3. Yay!..
Now you ask about the query foo( 2, [1,2,3], R) and how does R gets its value set correctly. The main thing missing from your rundown is the renaming of variables when a matching clause is selected. The resolution of the query goes like this:
|- foo( 2, [1,2,3], R) ? { }
%% SELECT -- 1st clause, with rename
|- ? { foo( H1, [H1|T1], T1) = foo( 2, [1,2,3], R) }
**FAIL** (2 = 1)
**BACKTRACK to the last SELECT**
%% SELECT -- 2nd clause, with rename
|- foo( X1, T1, R1) ?
{ foo( X1, [H1|T1], [H1|R1]) = foo( 2, [1,2,3], R) }
**OK**
%% REWRITE
|- foo( X1, T1, R1) ?
{ X1=2, [H1|T1]=[1,2,3], [H1|R1]=R }
%% REWRITE
|- foo( 2, [2,3], R1) ? { R=[1|R1] }
%% SELECT -- 1st clause, with rename
|- ? { foo( H2, [H2|T2], T2) = foo( 2, [2,3], R1), R=[1|R1] }
** OK **
%% REWRITE
|- ? { H2=2, T2=[3], T2=R1, R=[1|R1] }
%% REWRITE
|- ? { R=[1,3] }
%% DONE
The goals between |- and ? are the resolvent, the equations inside { } are the substitution. The knowledge base (KB) is implicitly to the left of |- in its entirety.
On each step, the left-most goal in the resolvent is chosen, a clause with the matching head is chosen among the ones in the KB (while renaming all of the clause's variables in the consistent manner, such that no variable in the resolvent is used by the renamed clause, so there's no accidental variable capture), and the chosen goal is replaced in the resolvent with that clause's body, while the successful unification is added into the substitution. When the resolvent is empty, the query has been proven and what we see is the one successful and-branch in the whole and-or tree.
This is how a machine could be doing it. The "rewrite" steps are introduced here for ease of human comprehension.
So we can see here that the first successful clause selection results in the equation
R = [1 | R1 ]
, and the second, --
R1 = [3]
, which together entail
R = [1, 3]
This gradual top-down instantiation / fleshing-out of lists is a very characteristic Prolog's way of doing things.
In response to the bounty challenge, regarding functional dependency in the relation foo/3 (i.e. select/3): in foo(A,B,C), any two ground values for B and C uniquely determine the value of A (or its absence):
2 ?- foo( A, [0,1,2,1,3], [0,2,1,3]).
A = 1 ;
false.
3 ?- foo( A, [0,1,2,1,3], [0,1,2,3]).
A = 1 ;
false.
4 ?- foo( A, [0,1,2,1,3], [0,1,2,4]).
false.
f ?- foo( A, [0,1,1], [0,1]).
A = 1 ;
A = 1 ;
false.
Attempt to disprove it by a counterargument:
10 ?- dif(A1,A2), foo(A1,B,C), foo(A2,B,C).
Action (h for help) ? abort
% Execution Aborted
Prolog fails to find a counterargument.
Tying to see more closely what's going on, with iterative deepening:
28 ?- length(BB,NN), foo(AA,BB,CC), XX=[AA,BB,CC], numbervars(XX),
writeln(XX), (NN>3, !, fail).
[A,[A],[]]
[A,[A,B],[B]]
[A,[B,A],[B]]
[A,[A,B,C],[B,C]]
[A,[B,A,C],[B,C]]
[A,[B,C,A],[B,C]]
[A,[A,B,C,D],[B,C,D]]
false.
29 ?- length(BB,NN), foo(AA,BB,CC), foo(AA2,BB,CC),
XX=[AA,AA2,BB,CC], numbervars(XX), writeln(XX), (NN>3, !, fail).
[A,A,[A],[]]
[A,A,[A,B],[B]]
[A,A,[A,A],[A]]
[A,A,[A,A],[A]]
[A,A,[B,A],[B]]
[A,A,[A,B,C],[B,C]]
[A,A,[A,A,B],[A,B]]
[A,A,[A,A,A],[A,A]]
[A,A,[A,A,B],[A,B]]
[A,A,[B,A,C],[B,C]]
[A,A,[B,A,A],[B,A]]
[A,A,[A,A,A],[A,A]]
[A,A,[B,A,A],[B,A]]
[A,A,[B,C,A],[B,C]]
[A,A,[A,B,C,D],[B,C,D]]
false.
AA and AA2 are always instantiated to the same variable.
There's nothing special about the number 3, so it is safe to conjecture by generalization that it will always be so, for any length tried.
Another attempt at Prolog-wise proof:
ground_list(LEN,L):-
findall(N, between(1,LEN,N), NS),
member(N,NS),
length(L,N),
maplist( \A^member(A,NS), L).
bcs(N, BCS):-
bagof(B-C, A^(ground_list(N,B),ground_list(N,C),foo(A,B,C)), BCS).
as(N, AS):-
bagof(A, B^C^(ground_list(N,B),ground_list(N,C),foo(A,B,C)), AS).
proof(N):-
as(N,AS), bcs(N,BCS),
length(AS,N1), length(BCS, N2), N1 =:= N2.
This compares the number of successful B-C combinations overall with the number of As they produce. Equality means one-to-one correspondence.
And so we have,
2 ?- proof(2).
true.
3 ?- proof(3).
true.
4 ?- proof(4).
true.
5 ?- proof(5).
true.
And so for any N it holds. Getting slower and slower. A general, unlimited query is trivial to write, but the slowdown seems exponential.

How to get value from a matrix in Prolog?

I'm a beginner in Prolog, so I'm still confused on how to form a recursive function in Prolog.
Let say I have a matrix:
S:
[ 5 6
3 4 ]
Represented in prolog as: S = [ [5,6], [3,4]].
I'm trying to write a recursive function to get a cell value such that cell_values (Cells, Matrix, Values) would return a list of the values from a list of the cell.
Example: cell_values ([[0,0], [0,1]], S, Values) --> Values = [5, 6]. Where S is the matrix above.
I'm thinking of using nth0 to get the value. This is my work so far.
:- use_module(library(clpfd)).
cell_values([], [], []).
cell_values([X|T], S, Values) :-
nth0(X, S, Row),
nth0(T, Row, Values).
Not sure how to fix this. Can you point me in the right direction?
There are some problems here with the predicate:
you use S and T as row number and column number, but S is the head of the list, and T the tail here. Since the list of indices is a list of lists, that means S will be a list, and T a list of lists;
you do not use recursion to generate a list of values, so if we fix the above, then it will still - at most - yield a specific value; and
the base predicate is too restrictive, since it assumes that the matrix (the second parameter), should be empty. This does not makes sense, since normally the matrix will be passed without any changes. Regardless of the matrix, if the list of indices is empty, then so is the list of values.
explicit recursion
So if we rewrite the predicate, there are two rules:
the base case: in case the list of indices is empty, then regardless of the matrix, the list of values is empty as well:
cell_values([], _, []).
in the recursive cass, we match the first list with [[R, C] | T], so R is the row number, and C the column number, T is the list of remaining lists to process, so we perform the nth0/3 as demonstrated in the question, but with R and C, and the cell value V is prepended to the result list [V|VT], the VT is then used in the recursive call to obtain more elements:
cell_values([[R, C]| T], M, [V|VT]) :-
nth0(R, M, Row),
nth0(C, Row, V),
cell_values(T, M, VT).
Or putting these together:
cell_values([], _, []).
cell_values([[R, C]| T], M, [V|VT]) :-
nth0(R, M, Row),
nth0(C, Row, V),
cell_values(T, M, VT).
maplist/3
Processing lists is a rather common thing to do, so we might be interested in using maplist/3, and write a predicate that only processes a single sublist, like:
cell_value(M, [R, C], V) :-
nth0(R, M, Row),
nth0(C, Row, V).
Then we can define the predicate cell_values like:
cell_values(Ixs, M, Vs) :-
maplist(cell_value(M), Ixs, Vs).

Making a list from a tuple

I am trying to make a list from a tuple of variable size. However, I am having trouble figuring out how to represent an empty tuple (or a tuple with a single value in it), which I need as my end case.
This is what I have right now which, judging by the trace, does create a list (reversed however but it's not really a problem) but it fails at the very end.
tuple_to_list((), []).
tuple_to_list((X, ()), [X]).
tuple_to_list((X, XS), List) :-
tuple_to_list(XS, [X|List]).
Just :
tuple_to_list((X, XS),[X | List]) :-
tuple_to_list(XS, List).
tuple_to_list((X), [X]):-
X \= (_,_).
Last clause X \= (,). because of
?- (X) = (a,b).
X = (a, b).

Last two elements of first list = first two elements of second list - Prolog

Trying to write Prolog rules that incorporates the following rules for a function matchFirstTwo(List1, List2), that evaluates to true if the last two elements of the first list = the first two elements of the second list. Append and reverse cannot be implemented into the solution.
last([X], X).
last([_|Z], X) :- last(Z, X).
nextToLast([X,_], X).
nextToLast([_|Z], X) :- nextToLast(Z, X).
Write matchFirstTwo(List1, List2) — succeeds exactly when List2's first and second elements equal List1's last two elements
% Example :
?- matchFirstTwo([a,b,c,d],[d,c,a,b]).
true.
Here's how we can define matchFirstTwo/2 using widely-available list predicates:
matchFirstTwo(List1, List2) :-
append([X,Y], _, List2), % List2's first and second elements
append(_, [Y,X], List1). % equal List1's last two elements
Or, more compactly:
matchFirstTwo(List1, [Y,X|_]) :-
append(_, [X,Y], List1).
Or, even better:
matchFirstTwo(List1, [Y,X|_]) :-
reverse(List1, [Y,X|_]).
Sample query:
?- matchFirstTwo([a,b,c,d], [d,c,a,b]).
true % succeeds deterministically
Keep removing the head of the first list and at the same time decrement length , if you have length of 2 then simply check for the solution.
Without append/3 and reverse/2
matchFirstTwo(List1,List2):-
length(List1,X),
match(List1,X,List2).
match(List1,2,List2):-
compare(List1,List2),!.
match([_|T],Len,List2):-
NewLength is Len - 1,
match(T,NewLength,List2).
compare([H1,H2|_],[H1,H2|_]).
You example query has a mistake, As you are trying to compare last two elements of first list with first two elements of second list. so second list must have [c,d,a,b] in-order to get true.

Why prolog outputs a weird tree-like list?

In this Prolog code I intend to list the first N primes,
(...)
biggerPrime(N,P) :-
isPrime(N),
P is N,
!.
biggerPrime(N,P) :-
N1 = N+1,
biggerPrime(N1,P).
primeListAcc(0,A,R,R) :- !.
primeList(N,L) :-
primeListAcc(N,1,[],L).
primeListAcc(N,A,L,R) :-
N1 is N-1,
biggerPrime(A,P),
A1 is P+1,
primeListAcc(N1,A1,[P|L],R).
And it works fine if I want the list ordered backwards:
?- primeList(5,L).
L = [11, 7, 5, 3, 2].
But if I change the last line of the code from [P|L] to [L|P] like this:
primeListAcc(N,A,L,R) :-
N1 is N-1,
biggerPrime(A,P),
A1 is P+1,
primeListAcc(N1,A1,[L|P],R).
I get:
?- primeList(5,L).
L = [[[[[[]|2]|3]|5]|7]|11].
What am I missing? This is driving me mad!
Recall that a list is either the empty list [] or a term with functor '.' and two arguments, whose second argument is a list. The syntax [P|Ps] is shorthand notation for the term '.'(P, Ps), which is a list if Ps is a list (as is the case in your example). The term '.'(Ps, P), on the other hand, which can also be written as [Ps|P] (as you are doing), is not a list if P is not a list. You can obtain a reverse list with reverse/2.
Great, so you've discovered the problem of adding elements to the end of a list. In Prolog, we can do it with
add(X,L,Z):- L=[X|Z].
wait, what? How to read this? We must know the calling convention here. We expect L and Z to come in as uninstantiated variables, and we arrange for L from now on to point to a newly created cons node with X at its head, and Z its tail. Z to be instantiated, possibly, in some future call.
IOW what we create here is an open-ended list, L = [X|Z] = [X, ...]:
primeList(N,L) :-
primeListAcc(N,1,[],L).
primeListAcc(N,A,Z,L) :- N > 0, % make it explicitly mutually-exclusive,
N1 is N-1, % do not rely on red cuts which are easily
biggerPrime(A,P), % invalidated if clauses are re-arranged!
A1 is P+1,
L = [P|R], % make L be a new, open-ended node, holding P
primeListAcc(N1,A1,Z,R). % R, the tail of L, to be instantiated further
primeListAcc(0,A,R,R). % keep the predicate's clauses together
We can see now that Z is not really needed here, as it carries the [] down the chain of recursive calls, unchanged. So we can re-write primeListAcc without the Z argument, so that its final clause will be
primeListAcc(0,A,R):- R=[].
Keeping Z around as uninstantiated variable allows for it to be later instantiated possibly with a non-empty list as well (of course, only once (unless backtracking occurs)). This forms the basis of "difference list" technique.
To answer your literal question - here, consider this interaction transcript:
1 ?- X=[a|b].
X = [a|b]
2 ?- X=[a|b], Y=[X|c].
X = [a|b]
Y = [[a|b]|c]
the [a|b] output is just how a cons node gets printed, when its tail (here, b) is not a list. Atoms, as numbers, are not lists.

Resources