A matrix is a rectangular array of numbers or other mathematical objects, for which operations such as addition and multiplication are defined.
因此,所有我們需要檢查的是,在基體中的所有行具有相同的尺寸。另請注意,有一個情況下,所謂的,空矩陣:
In some contexts, such as computer algebra programs, it is useful to consider a matrix with no rows or no columns, called an empty matrix.
is_matrix :: [[a]] -> Bool
-- Note, I removed the is_matrix [[]] = False condition
is_matrix (x:xs)
| null xs = True -- There are no more rows in sub-matrix - the answer is True
| length x == length (head xs) = is_matrix xs -- The same as in your version
| otherwise = False -- The same as in your version
此功能將產生以下輸出:
*Main> is_matrix [[]]
True
*Main> is_matrix [[1, 2, 3], [4, 5, 6]]
True
*Main> is_matrix [[1, 2, 3], [7], [4, 5, 6]]
此功能也可以在執行更自然的方式使用map
函數(the question about implementation of allTheSame
function):
*Main> let allTheSame xs = all (== head xs) (tail xs)
*Main> let isMatrix = allTheSame . map length
*Main> isMatrix [[]]
True
*Main> isMatrix [[1, 2, 3], [4, 5, 6]]
True
*Main> isMatrix [[1, 2, 3], [7], [4, 5, 6]]
False
那麼,'a'是什麼?我猜你實際上是指'長度x == 1',或者'isSingleton x',其中'isSingleton x = 1 x == x' – Zeta