Home > Blockchain >  Check if the matrix has at least one column and one row
Check if the matrix has at least one column and one row

Time:10-17

type Matrix = [[Rational]]


valid :: Matrix -> Bool
valid xs = uniform [length x | x <- xs] && length xs >= 1

I'm trying to test if a matrix has at least one row and one column and if all the rows are the same length, but when I input 'valid [[]]' into the terminal it outputs as true. Is there something wrong with the statement?

CodePudding user response:

I assume uniform is checking if all the elements in the list are the same. In the case of xs = [[]] the result of [length x | x <- xs] will be [0] which is a list where all elements are the same.

So you are missing a check that list elements are actually larger than 1. Since you already check that all the elements are the same, you should only need to check that the first element is at least 1.

Note that you might want to think about the order of your conditions. You should only check a property of the first element of a list after you know for sure that is at least one element in the list. Otherwise you might get an error if you give the input [].

CodePudding user response:

You can work with pattern matching to check if the list has at least one row, and that the first row has at least one column with:

valid :: Matrix -> Bool
valid xs@((_:_):_) = uniform (map length xs)
valid _ = False
  • Related