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 'string' may be col or string.
The idea is to add elements to the empty matrix lists. (for example, all elements of the first row = first elements of all columns => all elements of the first i-th row = i-th elements of all cols)
It works on my machine, as this session protocol shows:
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.