[英]Haskell Beginner, recursive function, list, Error: Non-exhaustive patterns
[英]Haskell - “Non-exhaustive patterns” error with a function using list
我試圖在haskell中使函數知道列表列表中的所有元素是否具有相同的長度。 (我在以前的帖子中搜索過答案,但是都沒有用)。
sameLength :: [[t]] -> String
sameLength [] = "Empty list"
sameLength [[items]]
| and $ map (\x -> length x == (length $ head [[items]])) [[items]] = "Same length"
| otherwise = "Not the same length"
問題是它不起作用:
*Main> :l test.hs
[1 of 1] Compiling Main ( test.hs, interpreted )
Ok, modules loaded: Main.
*Main> sameLength []
"Empty list"
*Main> sameLength [[1,2],[3,4]]
"*** Exception: test.hs:(2,1)-(5,39): Non-exhaustive patterns in function sameLength
*Main> sameLength [[1,2]]
"*** Exception: test.hs:(2,1)-(5,39): Non-exhaustive patterns in function sameLength
我真的不知道問題出在哪里。 它處理參數為空列表而不是空列表的情況。 我錯了嗎 ? 我錯過了什么 ?
謝謝你的幫助 :)
模式[x]
與僅包含一項x
的列表匹配。 因此,模式[[items]]
與包含單個項目的單個列表匹配。 您要在第二種情況下匹配所有非空列表。 但是,由於已經匹配了空列表,因此,通過消除,您只想匹配尚未匹配的任何內容。
sameLength :: [[t]] -> String
sameLength [] = "Empty list"
sameLength items = -- Code here
您在這里有太多[..]
:
sameLength [[items]]
(正如Silvio講得很好)-試試
sameLength items
代替。
此外,作為a == a
,您不必檢查頭部的長度是否與頭部的長度相同(當然),因此我建議您執行以下操作:
sameLength :: [[a]] -> Bool
sameLength [] = True
sameLength (h:tl) = all ((length h ==) . length) tl
我認為Bool
結果更加實用自然
all
接受一個謂詞和一個列表,並檢查謂詞是否對列表的每個元素都成立-因此(length h ==) . length = \\xs -> length h == length xs
(length h ==) . length = \\xs -> length h == length xs
作為謂詞,檢查給定列表xs
與頭列表h
是否具有相同的長度-因此,由於上述說明,您僅需與尾列表tl
進行檢查
您可以爭論空列表的所有元素是否應具有相同的長度 -但我認為答案應該是;)
Prelude> sameLength [[1,2],[3,4]]
True
Prelude> sameLength [[1,2],[3,4,5]]
False
Prelude> sameLength [[1,2]]
True
Prelude> sameLength []
True
(或者您不喜歡無重點款式)
sameLength :: [[a]] -> Bool
sameLength [] = True
sameLength (h:tl) = let l = length h
in all (\xs -> length xs == l) tl
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.