Why in SWI Prolog, I get the result with `|` sign? - list

I have the following code to group sequences of equivalent objects together:
pack([], []).
pack([X], [X]).
pack([H, T|TS], [H|TR]):-
H \= T,
pack([T|TS], TR).
pack([H, H|HS], [[H|TFR]|TR]):-
pack([H|HS], [TFR|TR]).
My input is:
pack([1,1,1,1,2,3,3,1,1,4,5,5,5,5], X).
And as a result I get:
[[1,1,1|1],2,[3|3],[1|1],4,[5,5,5|5]]
Have you noticed | sign before the last element in each list? I do not know why it appears and how to fix it. Any ideas?

A list is a data type that has two type of functors/constants:
the empty list [] which has no arguments; and
the "cons" [element|list].
As is denoted in the second option, the second parameter of a cons should be a list. This can be another cons (and thus recursively further), or an empty list. Nevertheless, Prolog is not really typed, so you can use an integer, character,... as second item, but then it is not a list.
So now the question is, "how do we construct such weird list". In this answer, I used a smaller example to reproduce the error, because it makes things easier:
?- trace.
true.
[trace] ?- pack([1,1], X).
Call: (7) pack([1, 1], _G1066) ? creep
Call: (8) 1\=1 ? creep
Fail: (8) 1\=1 ? creep
Redo: (7) pack([1, 1], _G1066) ? creep
Call: (8) pack([1], [_G1144|_G1141]) ? creep
Exit: (8) pack([1], [1]) ? creep
Exit: (7) pack([1, 1], [[1|1]]) ? creep
X = [[1|1]] .
If we thus pack two elements, something goes wrong. First we call pack([1,1],X).
First the third clause fires, but the H \= T item fails. So as a result Prolog redoes the call, but now with the last clause. In the last clause, we see something weird:
pack([H, H|HS], [[H|TFR]|TR]):-
pack([H|HS], [TFR|TR]).
What we see is that we perform a recursive call on pack/2 with [TFR|TR]. So that means [TFR|TR] should be a list of lists. But the second clause does not generate a list of lists, but only a list of items. So the error is in:
pack([X], [X]).
%% ^ list of items??
So what we need to do to resolve the error, is rewrite the second clause to:
pack([X], [[X]]).
%% ^ list of list
Now we have solved that problem, but we are still not there yet: there is also an type error in the third clause:
pack([H, T|TS], [H|TR]):-
%% ^ item instead of a list?
H \= T,
pack([T|TS], TR).
Again we can simply make it a list of items:
pack([H, T|TS], [[H]|TR]):-
%% ^ list
H \= T,
pack([T|TS], TR).
And now we obtain the following code:
pack([], []).
pack([X], [[X]]).
pack([H, T|TS], [[H]|TR]):-
H \= T,
pack([T|TS], TR).
pack([H, H|HS], [[H|TFR]|TR]):-
pack([H|HS], [TFR|TR]).
We then obtain:
?- pack([1,1,1,1,2,3,3,1,1,4,5,5,5,5], X).
X = [[1, 1, 1, 1], [2], [3, 3], [1, 1], [4], [5, 5, 5|...]] [write]
X = [[1, 1, 1, 1], [2], [3, 3], [1, 1], [4], [5, 5, 5, 5]] .
EDIT:
In case there is only one element, you apparently do not want to construct a list. That makes the problem a bit harder. There are two options:
we adapt the code such that if such element occurs, we do not add it to a list; or
we perform some post processing, where we "unlist" lists with one element.
The last one is quite trivial, so lets do the first one. In that case, the second clause should indeed read:
pack([X],[X]).
Now the second clause should read:
pack([H, T|TS], [H|TR]):-
H \= T,
pack([T|TS], TR).
as well. But the last clause, is harder:
pack([H, H|HS], [[H|TFR]|TR]):-
pack([H|HS], [TFR|TR]).
There are two possibilities here:
TFR is a list of items, in that case we simply prepend to the list; or
TFR is not a list, in which case we construct a list.
In order to solve this problem, we can define a predicate:
prepend_list(H,[HH|T],[H,HH|T]).
prepend_list(H,X,[H,X]) :-
X \= [_|_].
and then use:
pack([H, H|HS], [HTFR|TR]):-
pack([H|HS], [TFR|TR]),
prepend_list(H,TFR,HTFR).
So now we obtain:
pack([], []).
pack([X], [X]).
pack([H, T|TS], [H|TR]):-
H \= T,
pack([T|TS], TR).
pack([H, H|HS], [HTFR|TR]):-
pack([H|HS], [TFR|TR]),
prepend_list(H,TFR,HTFR).
prepend_list(H,[HH|T],[H,HH|T]).
prepend_list(H,X,[H,X]) :-
X \= [_|_].
Note however that this program will fail if you want to pack/2 lists itself. In that case you better use a post processing step anyway.
Now it constructs:
?- pack([1,1,1,1,2,3,3,1,1,4,5,5,5,5], X).
X = [[1, 1, 1, 1], 2, [3, 3], [1, 1], 4, [5, 5, 5|...]] [write]
X = [[1, 1, 1, 1], 2, [3, 3], [1, 1], 4, [5, 5, 5, 5]] .

Related

Prolog - Creating a list of all the possible shifts of another list?

For my assignment I need to create a list of all the possible shifts (rotations) of another list in prolog. For example,
Prototype: all_shifts(+A,-R,+L,+S) *S will always start at 1*
?- length([1,2,3,4],L), all_shifts([1,2,3,4],R,L,1).
L = 4,
R = [[2, 3, 4, 1], [3, 4, 1, 2], [4, 1, 2, 3]].
Currently, I have a program that shifts it to the left once.
one_shift(A, R) :-
rotate(left, A, R).
rotate(left, [H|T], L) :- append(T, [H], L).
However, I need to create another program in which the final result (R) contains all of the possible shifts. Recursion in prolog is really beginning to confuse me, but I'm pretty sure that's whats required. Any help would be really appreciated.
Stay logically pure using same_length/2 and append/3!
list_rotations(Es, Xss) :-
same_length(Es, [_|Xss]),
rotations_of(Xss, Es).
rotations_of([], _Es).
rotations_of([Xs|Xss], Es) :-
same_length([_|Xss], Suffix),
same_length(Es, Xs),
append(Suffix, Prefix, Xs),
append(Prefix, Suffix, Es),
rotations_of(Xss, Es).
Sample query:
?- list_rotations([A,B,C,D], Xss).
Xss = [[B,C,D,A],
[C,D,A,B],
[D,A,B,C]]. % succeeds deterministically
A solution to your problem could be:
rotatelist([H|T], R) :- append(T, [H], R).
rotate(L,LO,LL):-
rotatelist(L,L1),
\+member(L1,LO),!,
append([L1],LO,L2),
rotate(L1,L2,LL).
rotate(_,L,L).
?- rotate([1,2,3,4],[],L).
L = [[1, 2, 3, 4], [4, 1, 2, 3], [3, 4, 1, 2], [2, 3, 4, 1]]
Simply rotates the list and checks if this list has already been inserted in the output list. If not the recursion continues, otherwise it returns the list in L. I've inserted the cut ! just to have only the list with all the possible rotations. If you want generate also the other lists just remove it...
If instead you want a solution with the prototype you provide, it could be:
rotatelist([H|T], R) :- append(T, [H], R).
all_shifts(_,[],I,I).
all_shifts(L,Result,Len,I):-
I < Len,
rotatelist(L,LO),
I1 is I+1,
all_shifts(LO,R1,Len,I1),
append([LO],R1,Result).
?- length([1,2,3,4],L), all_shifts([1,2,3,4],R,L,1).
L = 4,
R = [[2, 3, 4, 1], [3, 4, 1, 2], [4, 1, 2, 3]]
The idea is basically the same as before... Note that this second solution is not tail recursive.

Prolog - How to make a list of lists with a certain length from a flat list

For example:
createlistoflists([1,2,3,4,5,6,7,8,9], NewLists)
NewLists = [[1,2,3], [4,5,6], [7,8,9].
So basically my first argument is a list, my second argument a new list consisting of lists with the proper length (the proper length being 3). My first idea was to use append of some sort. But I have literally no idea how to do this, any thoughts?
thanks in advance
If you don't mind using the nice facilities Prolog provides you, there's a simple approach;
list_length(Size, List) :- length(List, Size).
split_list(List, SubSize, SubLists) :-
maplist(list_length(SubSize), SubLists),
append(SubLists, List).
And you can query it as:
?- split_list([1,2,3,4,5,6,7,8,9], 3, L).
L = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
It will fail if List is instantiated in such a way that it's length is not a multiple of SubSize.
As pointed out by Will Ness in the comments, the above simple solution has a flaw: the maplist(list_length(SubSize), SubList) will continue to query and find longer and longer sets of sublists, unconstrained. Thus, on retry, the query above will not terminate.
The temptation would be to use a cut like so:
split_list(List, SubSize, SubLists) :-
maplist(list_length(SubSize), SubLists), !,
append(SubLists, List).
The cut here assumes you just want to get a single answer as if you were writing an imperative function.
A better approach is to try to constrain, in a logical way, the SubList argument to maplist. A simple approach would be to ensure that the length of SubList doesn't exceed the length of List since, logically, it should never be greater. Adding in this constraint:
list_length(Size, List) :- length(List, Size).
not_longer_than([], []).
not_longer_than([], [_|_]).
not_longer_than([_|X], [_|Y]) :-
not_longer_than(X, Y).
split_list(List, SubSize, SubLists) :-
not_longer_than(SubLists, List),
maplist(list_length(SubSize), SubLists),
append(SubLists, List).
Then the query terminates without losing generality of the solution:
?- split_list([1,2,3,4,5,6,7,8,9], 3, L).
L = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] ;
false.
?-
One could be more precise in the implementation of not_longer_than/2 and have it use the SubSize as a multiple. That would be more efficient but not required to get termination.
not_longer_than_multiple(L1, Mult, L2) :-
not_longer_than_multiple(L1, Mult, Mult, L2).
not_longer_than_multiple([], _, _, []).
not_longer_than_multiple([], _, _, [_|_]).
not_longer_than_multiple([_|Xs], Mult, 1, [_|Ys]) :-
not_longer_than_multiple(Xs, Mult, Mult, Ys).
not_longer_than_multiple(Xs, Mult, C, [_|Ys]) :-
C #> 1,
C1 #= C - 1,
not_longer_than_multiple(Xs, Mult, C1, Ys).
Or something along those lines...
But then, if we're going to go through all that non-sense to cover the sins of this use of maplist, then perhaps hitting the problem head-on makes the cleanest solution:
split_list(List, SubSize, SubLists) :-
split_list(List, SubSize, SubSize, SubLists).
split_list([], _, _, []).
split_list([X|Xs], SubList, 1, [[X]|S]) :-
split_list(Xs, SubList, SubList, S).
split_list([X|Xs], SubSize, C, [[X|T]|S]) :-
C #> 1,
C1 #= C - 1,
split_list(Xs, SubSize, C1, [T|S]).

Why is this row in prolog returning false?

I am trying to write a Prolog code, but I can't get this to return true. I am trying to find a list, which all elements are included in two other lists. For example all list A elements are found in B and C lists each, not together.
My Prolog code is :
member(X, [X|_]).
member(X, [_|T]) :-
member(X, T).
first([H0|T0], [H0|T1], A) :-
member(H0, A),
first(T0, [H0|T1], A).
first([H0|T0], [_|T1], A) :-
first([H0|T0], T1, A).
where member predicate returns true if an element is in a list. With predicate 'first' I am trying to use member predicate to find a matching element of A and B in C list. If I find, then go further in the first list and compare its first element to second lists elements and again, if I would matching, I check with if I can find it in third list. I hope it does this, but when I run
?- first([4, 6, 4], [4, 5, 6, 4], [1, 2, 4, 6]).
it gives false and I can't figure out why. This seems as a simple attention mistake somewhere, but I just can't get my head around it.
I don't know anything about prolog, but like everyone I've been bitten by logic errors before. (=
As I have commented, you seem to lack a base case for first([], _, _). An example:
first([4], [4], [4]) :-
member(4, [4]), // quite true
first([], [4], [4]). // No matching rule, as all those assume an existing head in the first argument
I am not sure I understood your question, but allow me to try to specify further your predicate first/3:
first(+L, +L1, +L2)
succeeds if every element of L is found either in L1 or in L2.
If this is what you're looking for, then:
first([], _, _).
first([E|L], L1, L2) :-
(member(E, L1); member(E, L2)),
first(L, L1, L2).
Examples of success:
first([1, 2, 3], [1, 2, 3], [1, 2]).
first([1], [1, 2, 3], [1, 2]).
first([1, 2, 3], [1, 2, 3], []).
Examples of faiure:
first([1, 2, 3, 5], [1, 2, 3], [1, 2]).
first([7], [1, 2, 3], [1, 2]).
first([1, 2, 3], [], []).

prolog two lists are exactly the same

I want to write a function that returns true if two lists are exactly the same(order of elements matters).
I tried it this way:
same([ ], [ ]).
same([H1|R1], [H2|R2]):-
H1 == H2,
same(R1, R2).
It returns true while two lists are the same, also I expect if I have
?- same(X, [1, 2, 3]).
I want it to return
X = [1, 2, 3].
But it doesn't work if input is like this. Here are some sample outputs I got:
?- same([1, 2], [1, 2]).
true.
?- same([2, 1], [1, 2]).
false.
?- same(X, [1, 2, 3]).
false.
?- same([1, 2, 3], [1, 2, X]).
false.
How to fix it?
The problem is that you're using ==/2 (checking whether two items are instantiated the same) rather than =/2 (checks if two items are unified or unifiable). Just change to unification:
same([], []).
same([H1|R1], [H2|R2]):-
H1 = H2,
same(R1, R2).
Then this will have the behavior you're looking for:
| ?- same(X, [1, 2, 3]).
X = [1,2,3] ? a
no
| ?- same([1, 2], [1, 2]).
(1 ms) yes
| ?- same([2, 1], [1, 2]).
no
| ?- same([1, 2, 3], [1, 2, X]).
X = 3
(1 ms) yes
| ?- same([A,B,C], L).
L = [A,B,C]
yes
% In this last example, A, B, and C are variables. So it says L is [A,B,C],
% whatever A, B, and C are.
If you query X == 3 in Prolog, and X is not bound to the value 3, or it is just unbound, it will fail. If X is unbound and you query, X = 3, then Prolog will unify X (bind it) with 3 and it will succeed.
For more regarding the difference between =/2 and ==/2, see What is the difference between == and = in Prolog?
You can also use maplist for a nice, compact solution. maplist is very handy for iterating through a list:
same(L1, L2) :- maplist(=, L1, L2).
Here, unification (=/2) is still used for exactly the same reason as above.
Finally, as #Boris points out, in Prolog, the unification predicate will work on entire lists. In this case, this would suffice:
same(L1, L2) :- L1 = L2.
Or equivalently:
same(L, L). % Would unify L1 and L2 queried as same(L1, L2)
This will succeed if the lists are the same, or will attempt to unify them by unifying each element in turn.
| ?- same([1,2,X], [1,2,3]). % Or just [1,2,X] = [1,2,3]
X = 3
yes
| ?- same([1,2,X], [1,2,3,4]). % Or just [1,2,X] = [1,2,3,4]
no
The prior more elaborate approaches are considered an exercise in list processing for illustration. But the simplest and most correct method for comparison and/or unification of lists would be L1 = L2.

Taking a tree and making a list

I have written a program that can take a list and change it into a tree.
build_tree([X,Y],'Tree'(X,Y)) :- !.
build_tree([X|Y],'Tree'(X,Z)) :- build_tree(Y, Z).
If I want to reverse the process and take the tree and change it back into a list, how would I do this?
Note that your tree->list conversion isn't a function since trees may correspond to multiple lists:
?- build_tree([1, 2, 3], T).
T = 'Tree'(1, 'Tree'(2, 3)).
?- build_tree([1, 'Tree'(2, 3)], T).
T = 'Tree'(1, 'Tree'(2, 3)).
If you want a predicate that can generate all lists from a tree, remove the cut from build_tree and apply it with a variable first argument. If you want a deterministic conversion, write a new predicate tree_to_list.
Just curious, how would that deterministic version play out? Assuming there was only one possible list, from the tree, for example:
('Tree'('Tree'(nil, 2, nil), 5, 'Tree'(nil, 6, nil)).
Which gives: L = [5, 2, 6]
If you remove the cut from the first rule, your code it's ready to work in 'backward' mode:
?- build_tree([1,2,3,4],T).
T = 'Tree'(1, 'Tree'(2, 'Tree'(3, 4))) ;
false.
?- build_tree(X,$T).
X = [1, 'Tree'(2, 'Tree'(3, 4))] ;
X = [1, 2, 'Tree'(3, 4)] ;
X = [1, 2, 3, 4] ;
false.
flatten(leaf, []).
flatten(node(L, E, R), Ls) :-
flatten(L, Ls1),
append(Ls1, [E], Ls2),
flatten(R, Ls3),
append(Ls2, Ls3, Ls).
if you consider tree ass node(leaf,Element,leaf) for example
flatten(node(node(leaf,2,leaf),3,node(leaf,5,leaf)),X).
gives X=[2,3,5].
and if you wanna have bst
List to Tree.
insert(E,leaf,node(leaf,E,leaf)).
insert(E,node(L,N,R),T) :-
E >= N,
T=node(L,N,R1),
insert(E,R,R1).
insert(E,node(L,N,R),T) :-
E < N,
T=node(L1,N,R),
insert(E,L,L1).
list_to_tree(List,Tree) :-
list_to_tree(List,leaf,Trea2),
Tree=Trea2.
list_to_tree([],Tree,Tree).
list_to_tree([H|T],Tree,St):-
insert(H,Tree,R),
list_to_tree(T,R,St).