Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transposing a Matrix in prolog

Tags:

prolog

I have written the following code below to transpose a Matrix in prolog

listFirst([],[]).
listFirst([H1|T1],[H2|Z]):-
    H1 = [H2|_],
    listFirst(T1,Z).

listFollowers([],[]).
listFollowers([H1|T1],[T2|Z]):-
    H1 = [H2|T2],
    listFollowers(T1,Z).

decompose(A,L1,L2):-
    listFollowers(A,L2),listFirst(A,L1).

transpose([],[]).
transpose([H|T],[L1|R]):-   
    decompose([H|T],L1,L2),
    transpose(L2,R).

Test Case

transpose([[1,2],[3,4],[5,6]], R).
R = [[1,3,5],[2,4,6]] ;

I am having problems with the transpose predicate no sure how to implement this. Other predicates seem to work okay.

like image 856
Krishna Kalyan Avatar asked Nov 17 '25 05:11

Krishna Kalyan


1 Answers

Taken from library(clpfd) in SWI-Prolog (see the source code for more information):

transpose([], []).
transpose([L|Ls], Ts) :- foldl(transpose_, L, Ts, [L|Ls], _).

transpose_(_, Fs, Lists0, Lists) :-
        maplist(list_first_rest, Lists0, Fs, Lists).

list_first_rest([L|Ls], L, Ls).

Example query:

?- transpose([[a,b,c],[d,e,f]], Ts).
Ts = [[a, d], [b, e], [c, f]].
like image 75
mat Avatar answered Nov 18 '25 19:11

mat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!