16
votes

I am writing some functions for graphs in Haskell, and I want to check if a list of integers, such as

[1,4, 5, 7]

contains vertices that make an edge, which i have represented as a tuple, like so

(1,5)

Im trying to take a function that takes the list and the tuple, and in this case would return true, because the list contains a 1 and a 5. The main issue i am having is that im really not sure how to search a list in Haskell. Is their a function that takes a list of type [a] and a value of type a, and returns a Bool, depending on whether [a] contains a?

2
their -> there, both in the post and in the pasted text for the link :)Riccardo T.
How about filter (==(1,5)) [(a,b)|a<-[1,4,5,7], b<-[1,4,5,7]] which you can make into a function very easily.fp_mora

2 Answers

38
votes

There is a function to check whether a value is in a list,

elem :: Eq a => a -> [a] -> Bool

Using that, your function is easily defined.

containsEdge :: [Int] -> (Int,Int) -> Bool
xs `containsEdge` (a,b) = (a `elem` xs) && (b `elem` xs)
8
votes

The elem function does that :

elem 1 [1,3,4]

will give True. Though this function is often used as an infix operator by surrounding it with backticks :

1 `elem` [1,4,5,7]

On the other hand, for big sets, that is not a very good idea (O(n) complexity), and you should use Set (or even IntSet if your elements are integers) instead of lists.