【发布时间】:2021-10-10 19:11:23
【问题描述】:
指定从列表中判断是否包含 0 的函数! 我该如何解决这个问题?
hasZero :: [Int] -> Bool
hasZero (0) = True
hasZero _ = False
【问题讨论】:
指定从列表中判断是否包含 0 的函数! 我该如何解决这个问题?
hasZero :: [Int] -> Bool
hasZero (0) = True
hasZero _ = False
【问题讨论】:
使用模式匹配并递归调用函数,同时始终检查头部元素是否为零,如果不是,则将其余元素向下传递到递归堆栈。如果找到零,该函数会提前返回 True。如果不是,它会调用整个列表并在遇到空列表基本情况时返回 False。
hasZero :: [Int] -> Bool
hasZero [] = False
hasZero (0:_) = True
hasZero (x:xs) = hasZero xs
【讨论】:
最简单的解决方案是使用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's answer:
hasZero :: [Int] -> Bool
hasZero (0:_) = True
hasZero (_:xs) = hasZero xs
hasZero [] = False
【讨论】: