[英]How to check for an empty intersection of lists with Haskell
Below is my code attempt for trying to create and then check the intersection of two lists in Haskell. 以下是我尝试创建然后检查Haskell中两个列表的交集的代码尝试。 Can someone help me get it to run? 有人可以帮我让它运行吗?
empty_intersection :: (Eq a_ => [a] -> [a] -> Bool
empty_intersection as bs = (true if ([x | x <- as, x `elem` bs) else false)
You've basically got the right idea here, there are just a few slight issues: 您基本上在这里有了正确的想法,这里只有几个小问题:
if
, since if
only works with values of type Bool
. if
不能直接使用列表,因为if
仅适用于Bool
类型的值。 You may perhaps be thinking of some other languages where lists/arrays are considered "true" if and only if they are non-empty - but Haskell does no automatic type conversions, so you have to explicitly check if the list is non-empty. 您可能会想到其他一些语言,其中且仅当列表/数组为非空时才将列表/数组视为“真”-但Haskell不会自动进行类型转换,因此您必须明确检查列表是否为非空。 The best and easiest way to do this is to use the null
function (which takes a list and returns True
if its empty, and False
otherwise). 做到这一点的最好和最简单的方法是使用null
函数(该函数接受一个列表,如果为空则返回True
,否则返回False
)。 (Eq a)
constraint. 正如@Bergi所指出的(我最初是想念的),您的(Eq a)
约束中有一个错字。 if
statement is backwards. if
语句向后。 Python has the construct x if (condition) else y
, but Haskell instead uses if condition then x else y
. Python具有结构x if (condition) else y
,但是Haskell却使用if condition then x else y
。 Also, although this isn't wrong, there's no need for it when your x
and y
are True
and False
, because the whole thing just evaluates to whatever (condition)
is. 另外,尽管这没错,但是当x
和y
为True
和False
时,则不需要它,因为整个结果的总和为(condition)
。 So the code should be: 因此,代码应为:
empty_intersection :: (Eq a) => [a] -> [a] -> Bool
empty_intersection as bs = null [x | x <- as, x `elem` bs]
Your code will not compile because a list cannot be a boolean, so you cannot have it in an if statement. 您的代码将无法编译,因为列表不能为布尔值,因此您不能将其包含在if语句中。 There are however functions like all
, any
and null
that can take lists and return booleans. 但是,有像all
, any
和null
这样的函数,它们可以获取列表并返回布尔值。
Just use the Prelude function null :: [a] -> Bool
which returns true if your list is empty. 只需使用Prelude函数null :: [a] -> Bool
,如果您的列表为空,则返回true。 (Also note as @Bergi said you have a typo in your type constraint) (还请注意,@ Bergi说您的类型约束中有错别字)
empty_intersection :: (Eq a => [a] -> [a] -> Bool
empty_intersection as bs = null [x | x <- as, x `elem` bs]
Also, as it's your second question on set unions and intersections, note that there is a library Data.Set
for dealing with ordered sets which has much more efficients functions for intersection, union, membership, difference, etc. 另外,由于这是关于集并集和交集的第二个问题,请注意,有一个用于处理有序集的库Data.Set
,它具有更高效的交集,并集,隶属关系, Data.Set
功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.