1

Good night everyone,

I'm in the middle of some busy days trying to deliver a small project for my Logic Programming classes, where the theme is based on operations on matrices.

Well, one of those asked operations was to verify if a certain element exists in a given matrix, and I'm having some issues with it as I usually have my mind set for imperative programming.

For now, i reached this:

isElemPresent(_, []) :- !.
isElemPresent(Elem, [M|Mt]) :- isElemPresent(Elem,Mt) ; isElemPresentRow(Elem,M).
isElemPresentRow(Elem, [Elem|_]).
isElemPresentRow(Elem, [_|T]) :- isElemPresentRow(Elem, T).

I would really appreciate if someone could guide to my goal, and if possible tell what lacks on my code.

2 Answers2

2
% The element belongs to the list if it matches
% the head of the list

isElemPresent(X,[X|_]).


% The element belongs to the list if it is 
% in the head (another array) of the list.

isElemPresent(X,[A|_]):- isElemPresent(X,A).


% The element belongs to the list if it is
% in the queue of the list.

isElemPresent(X,[_|R]):- isElemPresent(X,R).

For instance:

?- isElemPresent(4,[[1,2,5],[6,3,4]]).

Yes
TessellatingHeckler
  • 27,511
  • 4
  • 48
  • 87
0
is_elem_present(Elem, Matrix) :-
    member(Row, Matrix),
    member(Elem, Row).

?- is_elem_present(Elem, [[1,2,5],[6,3,4]]).
Elem = 1 ;
Elem = 2 ;
Elem = 5 ;
Elem = 6 ;
Elem = 3 ;
Elem = 4.

?- is_elem_present(2, [[1,2,5],[6,3,4]]).
true ;
false.

And here's how to do it with indexes:

is_elem_present(I, J, Elem, Matrix) :-
    nth0(I, Matrix, Row),
    nth0(J, Row, Elem).
?- forall(is_elem_present(I,J,Elem,[[1,2,5],[6,3,4]]), writeln([I,J]=Elem)).
[0,0]=1
[0,1]=2
[0,2]=5
[1,0]=6
[1,1]=3
[1,2]=4
true.
Peter Ludemann
  • 985
  • 6
  • 8