Home > Blockchain >  Is there a function in haskell to determine if each element in a list is in another list?
Is there a function in haskell to determine if each element in a list is in another list?

Time:05-27

I am wondering if there is a function in haskell to determine if each element in a list is in another list. I wrote my own, but it seems like something that would be in Prelude or Data.List

each :: Eq a => [a] -> [a] -> Bool
each xs ys = foldl (\acc x -> if x `elem` ys then True && acc else False) True xs

Does something like this already exist?

CodePudding user response:

The set operation you want specifically is not in the Prelude, but all makes the definition somewhat trivial (though not necessarily efficient).

-- Check if every element in xs is in ys (i.e., is xs a subset of ys)
each xs ys = all (`elem` ys) xs

Assuming your lists do not have duplicate values, you might try (\\).

import Data.List

-- Check if removing all elements in ys from xs produces an empty list.
each xs ys = null (xs \\ ys)
  • Related