簡體   English   中英

關於列表及其聲明的問題(haskell)

[英]Question about List and its Declaration(haskell)

我是 Haskell 的新手,我的一個程序有問題。 主要問題在聲明中,但我不知道如何正確編寫。 我需要檢查矩陣是否是實際矩陣,我的想法是檢查第一個列表中的元素數是否等於其他列表中的元素數。
提前致謝!

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

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

在您的代碼中,您傳入isMatrix function 兩個參數而不是一個參數,這就是您的代碼不起作用的原因。

你可以這樣寫:

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

所以,空矩陣和向量是矩陣。 否則,您將一一“刪除”行並檢查它們是否具有相同的長度。

PS您可以使用標准 function length而不是您的len

function 條款:

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

沒有多大意義,因為輸入類型是[[Int]] ,而不是兩個列表,所以 function 只能接受一個參數。

您可以檢查每行的長度是否等於下一行的長度:

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

您不需要自己實現length:: Foldable f => fa -> Int ,因為Prelude已經導出了它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM