Cartman
Cartman

Reputation: 68

transpose a matrix in prolog

I'm fairly new to Prologue and one of my first assignments in the class is to transpose a matrix in Prolog, meaning: If I have a matrix

A=[[1,2,3],[4,5,6],[7,8,9]]

I should get another matrix

S=[[1,4,7],[2,5,8],[3,6,9]].

I've written the code for it, however in the result I'm getting something like:

S=[[1,4,7],[2,5,8],[3,6,9], []].

(There is an empty list at the end of it). How do I correct something like that? Is my code completely wrong? I'm not supposed to use any non-standard tools (such as SWI-Prolog)

trans([],[]).
trans([S|R], [L|L1]) :-
    trans(S, R, L, M),
    trans(M, L1).

trans([], _,[],[]).
trans([S1|S2], [], [S1|L1], [S2|M]):-
    trans([], [], L1, M).
trans([S1|S2], [R1|R2], [S1|L1], [S2|M]):-
    trans(R1, R2, L1, M).

I've also seen and used the code provided here: How to transpose a matrix in prolog , however I wanted to try and write it myself.

Upvotes: 0

Views: 2227

Answers (1)

Tudor Berariu
Tudor Berariu

Reputation: 4910

One simple solution is to add another rule for predicate trans/2 to match that specific situation that in your case adds the empty list at the end.

trans([],[]).
trans([[]|_], []):-!.
trans([S|R], [L|L1]) :-
    trans(S, R, L, M),
    trans(M, L1).

Upvotes: 1

Related Questions