2

Considering that a matrix is a list of rows, how to check if my matrix is truly a matrix.

I need to write a predicate size(M, Row, Col). If is not a matrix, it should fail. If it is a matrix, it should count the number of rows and columns.

Sample queries with expected answer(s):

?- size([[1,2],[3,4],[5,6]], Rows, Cols).    
Rows = 3, Cols = 2.

?- size([[1,2],[3,4,5]], Rows, Cols).  
no

I have written the next code, where I simply get the number of Rows and the number of columns, but I do not know how to compare each row. If the length of the row are not the same, then it should return "no" and not print the number of Rows and Columns.

Code:

size([], 0, 0).
size(M, R, C) :-
    length(L, R).
size([H|T], R, N) :-
    length(H, N),
    !.
repeat
  • 18,496
  • 4
  • 54
  • 166
Saul Garcia
  • 890
  • 2
  • 9
  • 22
  • Yeah so i guess the reason for me to do `size(M, R, C) :- length(L, R).` Because I needed to get the length of the rows (Since each list is a row). I tried to implement the `same length` as you said, but I don't know how to compare each inner list and bail out if they are not the same. – Saul Garcia Dec 07 '15 at 22:44

1 Answers1

3

Simply proceed like this:

length_of(N, Ls) :-
   length(Ls, N).

size(Mss, R, C) :-
   length(Mss, R),
   maplist(length_of(C), Mss).

Sample queries:

?- size([[1,2],[3,4],[5,6]], Rows, Cols).
Rows = 3, Cols = 2.

?- size([[1,2],[3,4,5]], Rows, Cols).
false.
Community
  • 1
  • 1
repeat
  • 18,496
  • 4
  • 54
  • 166