指定從串列中決定是否包含 0 的函式!我怎樣才能解決這個問題 ?
hasZero :: [Int] -> Bool
hasZero (0) = True
hasZero _ = False
uj5u.com熱心網友回復:
使用模式匹配并遞回呼叫函式,同時始終檢查頭部元素是否為零,如果不是,則將其余元素向下傳遞到遞回堆疊。如果您找到零,該函式會提前回傳 True。如果不是,它會呼叫整個串列并在遇到空串列基本情況時回傳 False。
hasZero :: [Int] -> Bool
hasZero [] = False
hasZero (0:_) = True
hasZero (x:xs) = hasZero xs
uj5u.com熱心網友回復:
最簡單的解決方案是使用elem :: (Foldable f, Eq a) => a -> f a -> Bool. 在這種情況下,我們可以將其實作為:
hasZero :: [Int] -> Bool
hasZero xs = 0 `elem` xs
或者更簡單:
hasZero :: [Int] -> Bool
hasZero = elem 0
我們還可以利用any :: Foldable f => (a -> Bool) -> f a -> Bool:
hasZero :: [Int] -> Bool
hasZero = any (0 ==)
或者我們可以使用遞回并執行模式匹配,如@user1984 的回答:
hasZero :: [Int] -> Bool
hasZero (0:_) = True
hasZero (_:xs) = hasZero xs
hasZero [] = False
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/316818.html
上一篇:如何原子地修改可變陣列中的值?
下一篇:以三角形為中心(HASKELL)
