简体   繁体   English

如何检查两组的显式并集是否为空?

[英]How to check if the explicit union of two sets is empty?

Below is my code for the explicit union of two lists. 下面是我的两个列表的显式联合的代码。 How would I get the length of the list rather than the list itself? 我将如何获得列表的长度而不是列表本身?

explicit_union :: (Eq a) => [a] -> [a] -> [a]
explicit_union as bs = foldl (\as b -> if elem b as then as else as ++ [b]) as bs

The Union is empty if and only if both sets are empty. 当且仅当两个集合都为空时,联合为空。 So if you're computing the union just for that, you're wasting computational time. 因此,如果您只是为此计算联合,那是在浪费计算时间。

If instead you're given the union or have to use it anyways, length is the most natural method. 相反,如果为您提供了工会或仍然必须使用工会,则长度是最自然的方法。

However as you only want to know if it's empty, instead of length ls == 0 you can use take 1 ls == [] . 但是,由于您只想知道它是否为空,因此可以使用take 1 ls == []代替length ls == 0 This way Haskell -- as it's a lazy language -- only has to compute the first element, instead of the whole list as length would require 这样,Haskell(这是一种惰性语言)只需要计算第一个元素,而不需要计算整个列表(因为length需要)

Edit 编辑

As @joseph pointed out, there's a Prelude function to check if a list is null: null :: [a] -> Bool 正如@joseph指出的那样,有一个Prelude函数来检查列表是否为空: null :: [a] -> Bool

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM