How to transpose a matrix in prolog

cody picture cody · Nov 25, 2010 · Viewed 16.9k times · Source

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?

Answer

user206428 picture user206428 · Nov 25, 2010

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.