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 == []
. 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
As @joseph pointed out, there's a Prelude function to check if a list is null: null :: [a] -> Bool
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.