Reputation: 255
I need a predicate that given a list of lists (matrix)
removeElementM(Line,Column,List,NewList)
removes the (Line,Column) element.
For example given the List(L):
([a,b,c,d],
[e,r,t,y],
[u,i,o,t])
removeElementM(2,2,L,X) would return
X = [[a,b,c,d],[e,r,t,y],[u,i,t]]
I already have the stopping predicate
removeElementM(0,0,[[_|T1]|T],[T1|T]).
but cant't come up with the solution for the other one...
Upvotes: 2
Views: 1011
Reputation: 60004
nth0/4 as implemented in SWI-Prolog is rather powerful. You need to replace a row with another where the element has been deleted. Then
removeElementM(R, C, Mat, Upd) :-
nth0(R, Mat, OldRow, RestRows), % get the row and the rest
nth0(C, OldRow, _Val, NewRow), % we don't care the _Val deleted
nth0(R, Upd, NewRow, RestRows). % insert updated row in rest, get Upd matrix
test :-
L = [[a,b,c,d],
[e,r,t,y],
[u,i,o,t]],
removeElementM(2,2,L,X),
writeln(X).
?- test.
[[a,b,c,d],[e,r,t,y],[u,i,t]]
If you are learning Prolog, you are better to verify the answer from @joel76, it's basic Prolog without SWI-Prolog specific features.
Upvotes: 1
Reputation: 5635
Something like that :
removeElementM(Line,Column,[List | Rest],[List |NewList]) :-
Line > 0,
Line1 is Line - 1,
removeElementM(Line1, Column, Rest, NewList).
removeElementM(0, Column,[List | Rest],[List1 |Rest]) :-
removeElementL(Column, List, List1).
removeElementL(Column, [H | T], [H | T1]) :-
Column > 0,
Column1 is Column - 1,
removeElementL(Column1, T, T1).
removeElementL(0, [_H | T], T).
Upvotes: 2