[英]Haskell check if a list of lists has an empty list
I have tried to create a function that determines if a list of lists has an empty list.我试图创建一个 function 来确定列表列表是否有空列表。 However so far I don't seem to find any luck.但是到目前为止,我似乎还没有找到任何运气。 So far I have tried using: hasEmpty (x:xs) = if null x then True else False
However this only return true if the first list is empty.到目前为止,我已经尝试使用: hasEmpty (x:xs) = if null x then True else False
但是,如果第一个列表为空,这只会返回 true。 I also tried: hasEmpty (x:xs) = if null x || null xs then True else False
我也试过: hasEmpty (x:xs) = if null x || null xs then True else False
hasEmpty (x:xs) = if null x || null xs then True else False
But it produces the same result. hasEmpty (x:xs) = if null x || null xs then True else False
但它产生相同的结果。 I have also tried using any and elem but I couldn't get it working.我也尝试过使用any和elem ,但无法正常工作。 I am truly stumped on this.我真的很难过这一点。 Any help would be much appreciated任何帮助将非常感激
The type of any
is any:: Foldable t => (a -> Bool) -> ta -> Bool
(use :t any
) to get this. any 的类型是any
any:: Foldable t => (a -> Bool) -> ta -> Bool
(使用:t any
)来得到它。
There are two arguments:有两个arguments:
null
第一个参数是 function,它接受一个值并返回一个 boolean,例如null
Hence we can simply use any null
on a list.因此我们可以简单地使用列表中的any null
。
lst = [[1],[],[3]]
lst2 = [[1],[3],[2]]
any null lst -- returns True
any null lst2 -- returns False
Recursion always has a base case.递归总是有一个基本情况。 When you're dealing with lists, it's an empty list.当您处理列表时,它是一个空列表。 If we try running an anyNull
function on an empty list, it should return false.如果我们尝试在空列表上运行anyNull
function,它应该返回 false。
anyNull :: [a] -> Bool
anyNull [] = False
But we also need to match the non-empty list and converge toward the base case.但我们还需要匹配非空列表并向基本情况收敛。 This is done by recursively calling the function on the list's tail.这是通过递归调用列表尾部的 function 来完成的。 Fortunately pattern matching makes it easy to tell if the first element is an empty list, and then to handle the case where it is not empty.幸运的是,模式匹配可以很容易地判断第一个元素是否为空列表,然后处理它不为空的情况。
anyNull :: [a] -> Bool
anyNull [] = False
anyNull ([]:_) = True
anyNull (_:xs) = anyNull xs
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.