Search code examples
prolog

Prolog - Deleting Nth Row From A Matrix


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

Sample:

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

So far I was able to create this:

elimrow(1, [H|_], H).
elimrow(I, [H|T], X) :-
   I1 is I-1, elimrow(I1, T, X), delete(X, [H|T], B), writeln(B).

delete(A, [A|B], B).    
delete(A, [B, C|D], [B|E]) :- delete(A, [C|D], E).

This is currently able to select the row which I want to delete. However the delete function isn't functioning fully as expected.

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

It outputs the correct deleted array [[1,2], [5,6]], however it also outputs a X = [3,4]

I'm confused as to why there was a second output. (I only had one writeln(B)).

I also tried checking it with my first sample and it returned with false when it's not supposed to delete anything.

?- elimrow(-3, [[1,2],[3,4],[5,6]],X).
false.

Appreciate any help on this. Many thanks!


Solution

  • I think you make it too complicated. Your matrix is just a list of lists. So you can delete the I-th element of a list:

    eliminate(_, [], []).
    eliminate(0, [_|T], T).
    eliminate(I, [H|T], [H|R]) :-
        I > 0,
        I1 is I-1,
        eliminate(I1, T, R).