Matt
Matt

Reputation: 37

Check if the matrix has at least one column and one row

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?

Upvotes: 0

Views: 172

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477160

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

Upvotes: 1

Noughtmare
Noughtmare

Reputation: 10645

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 [].

Upvotes: 4

Related Questions