30pewpew
30pewpew

Reputation: 91

Prolog - Deleting Nth Column From A Matrix

I'm trying to create a query elimcol(_, [H|T], X) that deletes the nth column in a matrix array.

I believe that I'm complicating things as a beginner, but in Prolog logic, it would be better to call a matrix a "list of lists". So with that being said, since columns are essentially the "ith" element in every list of list, how would one go about deleting the ith element from all the lists, in a list of of lists. (I'm sorry for this confusing statement)

So far, this is what I was able to create:

elimcol(1, [G|H], H) :- !.
elimcol(N, [G|H], [G|L]) :- 
    N > 1, 
    Nn is N - 1,
    !,
    elimcol(Nn,H,L).

This is able to delete for one list. However when I tried to expand deleting more lists, it doesn't seem to delete the "ith element" anymore.

?- elimcol(3,[[1,2,3], [1,1,1], [4,5,6]], X).
X = [[1, 2, 3], [1, 1, 1]].

Appreciate any help on this. Many thanks!

EDIT: Did some minor changes, however same result i'm still only able to delete ith elements for (just one list)

elimcol(_, [], []).
elimcol(1, [_|T], T) :- !.
elimcol(I, [H|T], [H|R]) :-
   I1 is I-1,
   !, 
   elimcol(I1, T, R).

Upvotes: 1

Views: 183

Answers (1)

CapelliC
CapelliC

Reputation: 60024

maplist/N it's an idiomatic way to prove a relation among multiple lists elements, and nth1/4 can be used to discard the column from a row. Then

del_mat_col(M,N,M1) :-
    maplist(del_col(N),M,M1).
del_col(N,R,R1) :- nth1(N,R,_,R1).

yields

?- M=[[a,b,c],[d,e,f],[g,h,j]],del_mat_col(M,1,M1).
M = [[a, b, c], [d, e, f], [g, h, j]],
M1 = [[b, c], [e, f], [h, j]].

?- M=[[a,b,c],[d,e,f],[g,h,j]],del_mat_col(M,2,M1).
M = [[a, b, c], [d, e, f], [g, h, j]],
M1 = [[a, c], [d, f], [g, j]].

Using library(yall), the code becomes:

del_mat_col(M,N,M1) :-
    maplist({N}/[R,R1]>>nth1(N,R,_,R1),M,M1).

Upvotes: 2

Related Questions