Prolog sorting list using sort method - list

sort([ [30,100], [10,11] ], X).
gets
X = [[10,11],[30,100]]
How can I sort only by the first index of each sublist?
i.e
X = [[10,100], [30, 11]]
Thanks

The simpler way should be perusing the available builtins. Then take the first element from each sublist, sort them, and replace in the original:
sortfirst(L, S) :-
maplist(get_first, L, A),
msort(A, B),
maplist(set_first, L, B, S).
get_first([E|_], E).
set_first([_|R], E, [E|R]).
edit: note that msort is required, to avoid losing duplicates.
test:
?- sortfirst([ [30,100], [10,11] ], X).
X = [[10, 100], [30, 11]].
get/set first are just needed to adjust the arguments from maplist: if we use lambda, we can write a true 'one liner' procedure:
:- [lambda].
sortfirst_lambda(L, S) :-
maplist(\X^Y^(X = [E|_], Y = E), L, A),
msort(A, B),
maplist(\X^Y^Z^(X = [_|R], Y = E, Z = [E|R]), L, B, S).
Simple identities can simplify a little that expressions:
sortfirst_lambda(L, S) :-
maplist(\X^Y^(X = [Y|_]), L, A),
msort(A, B),
maplist(\X^Y^Z^(X = [_|R], Z = [Y|R]), L, B, S).
edit: or still more simplified:
sortfirst_lambda(L, S) :-
maplist(\[Y|_]^Y^true, L, A),
msort(A, B),
maplist(\[_|R]^Y^[Y|R]^true, L, B, S).
Here you can see that, as in the original get/set first, just the unification of arguments is needed.
Thus lambda it's syntactically convenient, but has its cost:
?- randomlists(100000, 3, -30,+30, L),
time(sortfirst(L,A)),
time(sortfirst_lambda(L,B)),
assertion(A=B).
% 400,012 inferences, 0,482 CPU in 0,483 seconds (100% CPU, 830072 Lips)
% 1,700,012 inferences, 1,717 CPU in 1,721 seconds (100% CPU, 990302 Lips)
L = [[-8, -13, 11], [-13, -27, -29], [5, 10, -24], [-8, -7, -6], [3, -24, -9], [-13, -20, -24], [7, 27|...], [-5|...], [...|...]|...],
A = B, B = [[-30, -13, 11], [-30, -27, -29], [-30, 10, -24], [-30, -7, -6], [-30, -24, -9], [-30, -20, -24], [-30, 27|...], [-30|...], [...|...]|...].
here are the service predicates to build sized test data:
randomlist(Length, Low, High, List) :-
findall(E, (between(1, Length, _),
random(Low, High, E)), List).
randomlists(Length1, Length2, Low, High, ListOfLists) :-
findall(E, (between(1, Length1, _),
randomlist(Length2, Low, High, E)), ListOfLists).

#chac(+1 btw): there's no need of lambda to one-line this (in swi at least!):
sortfirst(L, Res) :-
maplist(selectchk, X, L, R),
msort(X, XS),
maplist(selectchk, XS, Res, R).
but lambda versions or your first version are less tricky and more readable I think!

The below is my untested code.. there may be one/two cosmetic errors... The input list is split into two based on the head value on the list and the resulted two lists are recursively processed to finally result the sorted output.
sort(Input,Output):-sort(Input,[],Output).
sort([],SortedOut,SortedOut).
sort([[Index1,Index2]|Tail],SortedBig,Out):-
split(Tail,[Index1,Index2],LessList,BigList),
!,sort(BigList,SortedBig,NewSort),
sort(LessList,[[Index1,Index2]|NewSort],Out).
split([],[_D],[],[]).
split([[Index1,Index2]|Rem],[Index21,Index22],[[Index1,Index1]|L1],L2):-
Index1<Index21,
!,split(Rem,[Index21,Index22],L1,L2).
split([[Index1,Index2]|Rem],[Index21,Index22],L1,[[Index1,Index1]|L2]):-
!,split(Rem,[Index21,Index22],L1,L2).
Try this and let me know...

Related

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]).

Prolog merge two lists

I need to merge two lists in Prolog. On input should be predicate merge/3.
Should work like this:
?- merge([6,4,b,8], [5,b,s,6], X).
X = [6, 4, b, 8, 5, s].
What I have tried:
%rules
merge(A, B, X):-
merge(A, B, B, X).
merge([], X, _, X).
merge([Head|L1], [Head|L2], Tmp, [Head|X]) :-
merge(L1, L2, Tmp, X),
!.
merge(L1, [_|L2], Tmp, X) :-
merge(L1, L2, Tmp, X),
!.
merge([A|L1], [], Tmp, [A|X]) :-
merge(L1, Tmp, Tmp, X),
!.
What I get:
?- merge([1,2,a,3], [5,d,a,1], X).
X = [1, 2, a, 3, 5, d, a, 1].
What I expect:
?- merge([1,2,a,3], [5,d,a,1], X).
X = [1, 2, a, 3, 5, d].
If the order of the elements does not somehow depend on the order of the two input lists, this is an idiomatic Prolog solution:
?- append([6,4,b,8], [5,b,s,6], A), sort(A, B).
A = [6, 4, b, 8, 5, b, s, 6],
B = [4, 5, 6, 8, b, s].
If the order is important, you need to explain how exactly.
And some comments on the code you show. The names that you have chosen for your predicates: both "join" and "merge" have well-established meanings different from what you seem to be attempting to achieve ("join" as in relational databases, "merge" as in "merge two ordered lists"). What you are doing is rather a "union" (and by the way, click on this link and read the code!).
Also, it is almost always a mistake (not an error, but a mistake) to have a cut as the last subgoal of a clause body. Having multiple clauses to a predicate that are not obviously mutually exclusive (as the last 3 of the 4 clauses to your merge/4) is commonly a design flaw (not a mistake).
This can be done by rewriting built-in predicates ! e.g :
my_append([], R, R) .
my_append([H|T], R1, [H|R2]) :-
my_append(T, R1, R2).
my_member(H, [H|_]).
my_member(H, [_|T]) :-
my_member(H, T).
So, I can say that merging L with an empty list gives this list L
merge(L, [], L).
Now, to merge two lists, I look at the first element of the second list.
If it is in the first list, I ignore it and I merge the first list, with the rest of the second.
If not, I add this first element at the end of the first list and I merge the new first list with the rest of the second.
I must say that it's not very efficient !!
merge(L, [H| T], R) :-
( my_member(H, L)
-> merge(L, T, R)
; my_append(L, [H], L1),
merge(L1, T, R)).

Intersection and union of 2 lists

i'm starting up learning prolog (i use SWI-prolog) and i did a simple exercise in which i have 2 lists and i want to calculate their intersection and union.
Here is my code that works pretty well but i was asking myself if there is a better way to do it as i don't like to use the CUT operator.
intersectionTR(_, [], []).
intersectionTR([], _, []).
intersectionTR([H1|T1], L2, [H1|L]):-
member(H1, L2),
intersectionTR(T1, L2, L), !.
intersectionTR([_|T1], L2, L):-
intersectionTR(T1, L2, L).
intersection(L1, L2):-
intersectionTR(L1, L2, L),
write(L).
unionTR([], [], []).
unionTR([], [H2|T2], [H2|L]):-
intersectionTR(T2, L, Res),
Res = [],
unionTR([], T2, L),
!.
unionTR([], [_|T2], L):-
unionTR([], T2, L),
!.
unionTR([H1|T1], L2, L):-
intersectionTR([H1], L, Res),
Res \= [],
unionTR(T1, L2, L).
unionTR([H1|T1], L2, [H1|L]):-
unionTR(T1, L2, L).
union(L1, L2):-
unionTR(L1, L2, L),
write(L).
Keep in mind that i want to have just 1 result, not multiple results (even if correct) so running the code with this:
?- intersect([1,3,5,2,4] ,[6,1,2]).
should exit with:
[1,2]
true.
and not with
[1,2]
true ;
[1,2]
true ;
etc...
The same must be valid for union predicate.
As i said my code works pretty well but please suggest better ways to do it.
Thanks
Also, not sure why you're dead against cuts, so long as their removal would not change the declaritive meaning of the code, as per your link. For example:
inter([], _, []).
inter([H1|T1], L2, [H1|Res]) :-
member(H1, L2),
inter(T1, L2, Res).
inter([_|T1], L2, Res) :-
inter(T1, L2, Res).
test(X):-
inter([1,3,5,2,4], [6,1,2], X), !.
test(X).
X = [1, 2].
In the test bit where I call the code, I'm just saying do the intersection but I'm only interested in the first answer. There are no cuts in the predicate definitions themselves.
The following is based on my previous answer to Remove duplicates in list (Prolog);
the basic idea is, in turn, based on #false's answer to Prolog union for A U B U C.
What message do I want to convey to you?
You can describe what you want in Prolog with logical purity.
Using if_/3 and (=)/3 a logically pure implementation can be
both efficient (leaving behind choice points only when needed)
and monotone (logically sound with regard to generalization / specialization).
The implementation of #false's predicates if_/3 and (=)/3 does use meta-logical Prolog features internally, but (from the outside) behaves logically pure.
The following implementation of list_list_intersection/3 and list_list_union/3 uses list_item_isMember/3 and list_item_subtracted/3, defined in a previous answer:
list_list_union([],Bs,Bs).
list_list_union([A|As],Bs1,[A|Cs]) :-
list_item_subtracted(Bs1,A,Bs),
list_list_union(As,Bs,Cs).
list_list_intersection([],_,[]).
list_list_intersection([A|As],Bs,Cs1) :-
if_(list_item_isMember(Bs,A), Cs1 = [A|Cs], Cs1 = Cs),
list_list_intersection(As,Bs,Cs).
Here's the query you posted as part of your question:
?- list_list_intersection([1,3,5,2,4],[6,1,2],Intersection).
Intersection = [1, 2]. % succeeds deterministically
Let's try something else... The following two queries should be logically equivalent:
?- A=1,B=3, list_list_intersection([1,3,5,2,4],[A,B],Intersection).
A = 1,
B = 3,
Intersection = [1, 3].
?- list_list_intersection([1,3,5,2,4],[A,B],Intersection),A=1,B=3.
A = 1,
B = 3,
Intersection = [1, 3] ;
false.
And... the bottom line is?
With pure code it's easy to stay on the side of logical soundness.
Impure code, on the other hand, more often than not acts like "it does what it should" at first sight, but shows all kinds of illogical behaviour with queries like the ones shown above.
Edit 2015-04-23
Neither list_list_union(As,Bs,Cs) nor list_list_intersection(As,Bs,Cs) guarantee that Cs doesn't contain duplicates. If that bothers you, the code needs to be adapted.
Here are some more queries (and answers) with As and/or Bs containing duplicates:
?- list_list_intersection([1,3,5,7,1,3,5,7],[1,2,3,1,2,3],Cs).
Cs = [1, 3, 1, 3].
?- list_list_intersection([1,2,3],[1,1,1,1],Cs).
Cs = [1].
?- list_list_union([1,3,5,1,3,5],[1,2,3,1,2,3],Cs).
Cs = [1, 3, 5, 1, 3, 5, 2, 2].
?- list_list_union([1,2,3],[1,1,1,1],Cs).
Cs = [1, 2, 3].
?- list_list_union([1,1,1,1],[1,2,3],Cs).
Cs = [1, 1, 1, 1, 2, 3].
Edit 2015-04-24
For the sake of completeness, here's how we could enforce that the intersection and the union are sets---that is lists that do not contain any duplicate elements.
The following code is pretty straight-forward:
list_list_intersectionSet([],_,[]).
list_list_intersectionSet([A|As1],Bs,Cs1) :-
if_(list_item_isMember(Bs,A), Cs1 = [A|Cs], Cs1 = Cs),
list_item_subtracted(As1,A,As),
list_list_intersectionSet(As,Bs,Cs).
list_list_unionSet([],Bs1,Bs) :-
list_setB(Bs1,Bs).
list_list_unionSet([A|As1],Bs1,[A|Cs]) :-
list_item_subtracted(As1,A,As),
list_item_subtracted(Bs1,A,Bs),
list_list_unionSet(As,Bs,Cs).
Note that list_list_unionSet/3 is based on list_setB/2, defined here.
Now let's see both list_list_intersectionSet/3 and list_list_unionSet/3 in action:
?- list_list_unionSet([1,2,3,1,2,3,3,2,1],[4,5,6,2,7,7,7],Xs).
Xs = [1, 2, 3, 4, 5, 6, 7].
?- list_list_intersectionSet([1,2,3,1,2,3,3,2,1],[4,5,6,2,7,7,7],Xs).
Xs = [2].
Edit 2019-01-30
Here is an additional query taken from #GuyCoder's comment (plus two variants of it):
?- list_list_unionSet(Xs,[],[a,b]).
Xs = [a,b]
; Xs = [a,b,b]
; Xs = [a,b,b,b]
...
?- list_list_unionSet([],Xs,[a,b]).
Xs = [a,b]
; Xs = [a,b,b]
; Xs = [a,b,b,b]
...
?- list_list_unionSet(Xs,Ys,[a,b]).
Xs = [], Ys = [a,b]
; Xs = [], Ys = [a,b,b]
; Xs = [], Ys = [a,b,b,b]
...
With the old version of list_item_subtracted/3, above queries didn't terminate existentially.
With the new one they do.
As the solution set size is infinite, none of these queries terminate universally.
To cheat slightly less than my first answer, you could use the findall higher order predicate which gets Prolog to do the recursion for you :
4 ?- L1=[1,3,5,2,4], L2=[6,1,2], findall(X, (nth0(N, L1, X), member(X, L2)), Res).
L1 = [1, 3, 5, 2, 4],
L2 = [6, 1, 2],
Res = [1, 2].
If the aim is to just 'get the job done', then swi prolog has built in primitives for exactly this purpose:
[trace] 3 ?- intersection([1,3,5,2,4] ,[6,1,2], X).
intersection([1,3,5,2,4] ,[6,1,2], X).
X = [1, 2].
[trace] 4 ?- union([1,3,5,2,4] ,[6,1,2], X).
X = [3, 5, 4, 6, 1, 2].
Try this, analogue to union/3 here:
:- use_module(library(clpfd)).
member(_, [], 0).
member(X, [Y|Z], B) :-
(X #= Y) #\/ C #<==> B,
member(X, Z, C).
intersect([], _, []).
intersect([X|Y], Z, T) :-
freeze(B, (B==1 -> T=[X|R]; T=R)),
member(X, Z, B),
intersect(Y, Z, R).
It works if the elements are integer, and doesn't leave any choise point:
?- intersect([X,Y],[Y,Z],L).
freeze(_15070, (_15070==1->L=[X, Y];L=[Y])),
_15070 in 0..1,
_15166#\/_15168#<==>_15070,
_15166 in 0..1,
X#=Y#<==>_15166,
X#=Z#<==>_15168,
Y#=Z#<==>_15258,
_15168 in 0..1,
_15258 in 0..1.
?- intersect([X,Y],[Y,Z],L), X=1, Y=2, Z=3.
X = 1,
Y = 2,
Z = 3,
L = [2].
?- intersect([X,Y],[Y,Z],L), X=3, Y=2, Z=3.
X = Z, Z = 3,
Y = 2,
L = [3, 2].
And finally (really), you could use findall to find all the solutions, then use nth0 to extract the first one, which will give you the result you want without cuts, and keeps the predicates nice and clean, without have any additional predicates to trap/stop prolog doing what it does best - backtracking and finding multiple answers.
Edit: It's arguable that putting in extra predicates in the 'core logic' to prevent multiple results being generated, is as ugly/confusing as using the cuts that you are trying to avoid. But perhaps this is an academic exercise to prove that it can be done without using higher order predicates like findall, or the built-ins intersection/union.
inter([], _, []).
inter([H1|T1], L2, [H1|Res]) :-
member(H1, L2),
inter(T1, L2, Res).
inter([_|T1], L2, Res) :-
inter(T1, L2, Res).
test(First):-
findall(Ans, inter([1,3,5,2,4], [6,1,2], Ans), Ansl),
nth0(0, Ansl, First).
% Element X is in list?
pert(X, [ X | _ ]).
pert(X, [ _ | L ]):- pert(X, L).
% Union of two list
union([ ], L, L).
union([ X | L1 ], L2, [ X | L3 ]):- \+pert(X, L2), union(L1, L2, L3).
union([ _ | L1 ], L2, L3):- union(L1, L2, L3).
% Intersection of two list
inter([ ], _, [ ]).
inter([ X | L1 ], L2, [ X | L3 ]):- pert(X, L2), inter(L1, L2, L3).
inter([ _ | L1 ], L2, L3):- inter(L1, L2, L3).
I know this post is very old but I found a solution with minimum coding.
% intersection
intersection([],L1,L2,L3).
intersection([H|T],L2,L3,[H|L4]):-member(H,L2),intersection(T,L3,L3,L4).
% member
member(H,[H|T]).
member(X,[H|T]):-member(X,T).
To test the above code you should not enter L3. Here is an examples.
?- intersection([w,4,g,0,v,45,6],[x,45,d,w,30,0],L).
L = [w, 0, 45].

Prolog list problem

[a,b,c,d] and
[[1,2,3,4],[5,6,7,8],[43,34,56,5],[23,32,2,2]]
I want to make
[[a,1,2,3,4],[b,5,6,7,8],[c,43,34,56,5],[d,23,32,2,2]]
I use swi prolog is it possible do it ?
Thanks a lot.
solve([], [], []).
solve([[X|Y]|S], [X|L1], [Y|L2]):-
solve(S, L1, L2).
UPDATE: How to use
Write the function in a file "a.pl", then in swi-prolog type:
['a.pl'].
then type:
solve(X, [a,b,c,d], [[1,2,3,4],[5,6,7,8],[43,34,56,5],[23,32,2,2]]).
You will get:
X = [[a, 1, 2, 3, 4], [b, 5, 6, 7, 8], [c, 43, 34, 56, 5], [d, 23, 32, 2, 2]]
I have the strange feeling that I am doing your homework. Is it?
Use meta-predicate maplist/4 and Prolog lambdas like this:
?- As = [a,b,c,d],
Bss = [[1,2,3,4],[5,6,7,8],[43,34,56,5],[23,32,2,2]],
maplist(\H^T^[H|T]^true,As,Bss,Css).
As = [ a , b , c , d ],
Bss = [[ 1,2,3,4],[ 5,6,7,8],[ 43,34,56,5],[ 23,32,2,2]],
Css = [[a,1,2,3,4],[b,5,6,7,8],[c,43,34,56,5],[d,23,32,2,2]].
Edit
Different lambda terms can be used in above maplist/4 goal, as pointed out in a comment.
maplist(\H^T^[H|T]^true,As,Bss,Css)
maplist(\H^T^ =([H|T]) ,As,Bss,Css)
SWI Prolog can do this with two short predicates:
merge0(A, B, Prev, Next) :- append(Prev, [[A|B]], Next).
merge(A, B, Result) :- foldl(merge0, A, B, [], Result).
Here is example of input and output:
a(X) :- X = [a,b,c,d].
b(X) :- X = [[1,2,3,4],[5,6,7,8],[43,34,56,5],[23,32,2,2]].
?- a(A), b(B), merge(A, B, Result).
Result = [[a, 1, 2, 3, 4], [b, 5, 6, 7, 8], [c, 43, 34, 56, 5], [d, 23, 32, 2, 2]].
try this:
delete(X, [X|T], T).
delete(X, [Y|T], [Y|L]):-
delete(X, T, L).
insert(X, List, BigList):-
delete(X, BigList, List).
if([],X,X).
if([H1|T1],[H2|T2],[SH|ST]):-
insert(H1,H2,SH),!,
if(T1,T2,ST).
I doubled checked, it works.
"if" stands for "insert first".

How to transpose a matrix in prolog

How can I transpose a list like [[1,2,3][4,5,6][6,7,8]] to [[1,4,6],[2,7,8],[3,6,9]]?
To depict it: I'd like to flip the matrix 90 degree to the left. How can I do that?
Not sure your example is correct, but I get the idea.
If using SWI-PROLOG, you can use the CLPFD module, like so:
:- use_module(library(clpfd)).
Allowing you to use the transpose/2 predicate, like this:
1 ?- transpose([[1,2,3],[4,5,6],[6,7,8]], X).
X = [[1, 4, 6], [2, 5, 7], [3, 6, 8]].
Otherwise (if no SWI-PROLOG), you could simply use this implementation (which happened to be an old one in SWI's clpfd):
transpose([], []).
transpose([F|Fs], Ts) :-
transpose(F, [F|Fs], Ts).
transpose([], _, []).
transpose([_|Rs], Ms, [Ts|Tss]) :-
lists_firsts_rests(Ms, Ts, Ms1),
transpose(Rs, Ms1, Tss).
lists_firsts_rests([], [], []).
lists_firsts_rests([[F|Os]|Rest], [F|Fs], [Os|Oss]) :-
lists_firsts_rests(Rest, Fs, Oss).
For an updated version which uses foldl and maplist built-ins, see clpfd.pl.
This is the smallest solution I could come up with.
Code
transpose([[]|_], []).
transpose(Matrix, [Row|Rows]) :- transpose_1st_col(Matrix, Row, RestMatrix),
transpose(RestMatrix, Rows).
transpose_1st_col([], [], []).
transpose_1st_col([[H|T]|Rows], [H|Hs], [T|Ts]) :- transpose_1st_col(Rows, Hs, Ts).
Test
:- transpose([[1,2,3],
[4,5,6],
[7,8,9]], R),
print(R).
Prints:
[[1,4,7],
[2,5,8],
[3,6,9]]
Explanation
The way it works is that transpose will recursively call transpose_1st_col which extracts and transposes the first column of the matrix. For example:
:- transpose_1st_col([[1,2,3],
[4,5,6],
[7,8,9]], Row, RestMatrix),
print(Row),
print(RestMatrix).
will print
[1,4,7]
and
[[2,3],
[5,6],
[8,9]]
This is repeated until the input matrix is empty, at which point all columns have been transposed. The transposed columns are then joined into the transposed matrix.
Here's a fragment of a larger answer:
% transposed(+A, ?B) iff matrix B is transposed matrix A
transposed(A, B) :- transposed(A, [], B).
transposed(M, X, X) :- empty(M), !.
transposed(M, A, X) :- columns(M, Hs, Ts), transposed(Ts, [Hs|A], X).
% empty(+A) iff A is empty list or a list of empty lists
empty([[]|A]) :- empty(A).
empty([]).
% columns(+M, ?Hs, ?Ts) iff Hs is the first column
% of matrix M and Ts is the rest of matrix M
columns([[Rh|Rt]|Rs], [Rh|Hs], [Rt|Ts]) :- columns(Rs, Hs, Ts).
columns([[]], [], []).
columns([], [], []).
simpler approach:
trans(M, [P|T]):- first(M, P, A), trans(A, T).
trans(Empty, []):- empty(Empty).
empty([[]|T]):- empty(T).
empty([[]]).
first([[P|A]|R], [P|Ps], [A|As]):- first(R, Ps, As).
first([], [], []).
efficient also
[debug] 36 ?- time(trans([[1,2,3],[4,5,6],[7,8,9]],A)).
% 21 inferences, 0.000 CPU in 0.000 seconds (?% CPU, Infinite Lips)
A = [[1,4,7],[2,5,8],[3,6,9]] ;
% 12 inferences, 0.000 CPU in 0.000 seconds (?% CPU, Infinite Lips)
false.
Another simple approach:
transpose(M0, M) :-
nonvar(M0),
findall(L, maplist(nth1(_), M0, L), M).
?- transpose([[1,2,3],[4,5,6],[7,8,9]], M).
M = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]. `
An iterative approach:
trans([H|R],[H1|R1]):-trans2([H|R],[H|R],[],[H1|R1],0),!.
trans2([A|_],_,_,[],N):-length(A,N).
trans2(M,[],H1,[H1|R1],N):-N1 is N+1, trans2(M,M,[],R1,N1).
trans2(M,[H|R],L,[H1|R1],N):-nth0(N,H,X),
append(L,[X],L1),trans2(M,R,L1,[H1|R1],N).
My solution with full names for a better understanding:
% emptyMatrix(Line, EmptyMatrix)
emptyMatrix([],[]).
emptyMatrix([_|T1],[[]|T2]):-emptyMatrix(T1,T2).
% only length of parameter 'Line' is interesting. It ignores its content.
% appendElement(Element, InputList, OutputList)
appendElement(E,[],[E]).
appendElement(E,[H|T],[H|L]):-appendElement(E,T,L).
% appendTransposed(NestedList, InputMatrix, OutputMatrix)
appendTransposed([],[],[]).
appendTransposed([X|T1],[],[[X]|T3]):-appendTransposed(T1,[],T3).
appendTransposed([X|T1],[R|T2],[C|T3]):-appendElement(X,R,C),appendTransposed(T1,T2,T3).
% transposeMatrix(InputMatrix, TransposedMatrix)
transposeMatrix([L|M],T):-emptyMatrix(L,A),transpose([L|M],T,A).
transpose([],T,T).
transpose([L|M],T,A):-appendTransposed(L,A,B),transpose(M,T,B).
A 'line' can be a col or a row.
The idea lies in appending the elements into the lists of an empty matrix.
(e.g. all elements of the first row = the first elements of all cols
=> all elements of the first i-nth row = the i-nth elements of all cols)
It works on my machine as this session protocol shows to me:
5 ?- transposeMatrix([[1,2],[3,4]],T).
T = [[1, 3], [2, 4]] ;
false.
6 ?- transposeMatrix([[1],[2]],T).
T = [[1, 2]] ;
false.
7 ?- transposeMatrix([[1,2,3],[4,5,6]],T).
T = [[1, 4], [2, 5], [3, 6]] ;
false.
8 ?- transposeMatrix([[1]],T).
T = [[1]] ;
false.
Another approach:
delete_one_list([], []).
delete_one_list([[_|L]|LLs], [L|Ls]) :-
delete_one_list(LLs, Ls).
transpose_helper([], []).
transpose_helper([[X|_]|Xs], [X|Ys]) :-
transpose_helper(Xs, Ys).
transpose([[]|_], []).
transpose(List, [L|Ls]) :-
transpose_helper(List, L),
delete_one_list(List, NewList),
transpose(NewList, Ls).