Search code examples
matrixprologfindelement

Verify if an element is present in a matrix in ProLog


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.


Solution

  • % 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