Question about List and its Declaration(haskell)

Viewed 102

I am new to Haskell and I have a problem with one program. The main problem is in the declaration, but I don't know how to write it properly. I need to check if the matrix is an actual matrix and my idea is to check if the number of elements in the first list is equal to the number of elements in the other lists.
Thanks in advance!

isMatrix ::[[Int]] -> Bool
isMatrix [] _ = False
isMatrix xs ys | ((len xs) == (len ys)) = True
               | otherwise = False

len :: [Int] -> Int
len [] = @
len (_:zs) = 1+ len zs
2 Answers

In your code you pass in isMatrix function two argument instead of one, that's why your code don't work.

You can write it so:

isMatrix :: [[Int]] -> Bool
isMatrix [] = True
isMatrix [_] = True
isMatrix (r1:r2:rs) = len r1 == len r2 && isMatrix (r2:rs)

So, empty matrix and vector is matrix. Otherwise you "delete" rows one by one and check that they have the same length.

P. S. You can use standart function length instead of your len.

The function clauses:

isMatrix [] _ = False
isMatrix xs ys
    | len xs == len ys = True
    | otherwise = False

do not make much sense, since the input type is an [[Int]], not two lists, so the function can only accept one parameter.

You can check if the length of each row is equal to the length of the next row with:

isMatrix :: Foldable f => [f a] -> Bool
isMatrix xss = and (zipWith (==) rs (tail rs))
    where rs = map length xss

You do not need to implement length :: Foldable f => f a -> Int yourself, since that is already exported by the Prelude.

Related