--這一行統計串列中有多少個0
hasZero :: [Int] -> Bool
hasZero x = 0 < sum [1 | y <- x, y == 0]
--在這一行中,我想計算串列中有多少個空串列,但我編譯錯誤。
hasEmpty :: [[a]] -> Bool
hasEmpty x = 0 < [1 | y <- [x], y == []]
uj5u.com熱心網友回復:
您的第二種方法有兩個問題-您缺少第一種方法sum中的計數,并且您將傳遞的串列包裝到另一個方法中,它應該y <- x與第一種方法一樣:
hasEmpty :: [[a]] -> Bool
hasEmpty x = 0 < sum [1 | y <- x, null y]
可以重寫為:
hasEmpty :: [[a]] -> Bool
hasEmpty = any null
uj5u.com熱心網友回復:
在第一個示例中,您將串列推導生成的串列元素相加。第二,你還沒有這樣做。您也不需要放在x括號中。
hasEmpty :: Eq a => [[a]] -> Bool
hasEmpty x = 0 < sum [1 | y <- x, y == []]
這是實作這一目標的一種特殊方式。更慣用的方法(除了使用現有的 Prelude 函式any)是使用模式匹配和遞回。
hasZero :: [Int] -> Bool
hasZero [] = True
hasZero (0:_) = True
hasZero (_:xs) = hasZero xs
使用any:
hasZero :: [Int] -> Bool
hasZero = any (== 0)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/512321.html
標籤:哈斯克尔
